JS executes code

Why does this code report an error?

Mar.21,2021

What does the expression

var x = xx; do? He first declares a variable in memory, where the variable is not processed, so the value is undefined, and then assigns the result on the right to the variable on the left.

in your example, first declare a variable obj, in memory, and then look on the right, and on the right is an object, so it opens up a space in heap memory to save the object, and when it reads name:'js' , it assigns a value to the name attribute of the object. When reading to the next line, because the can attribute corresponds to an immediate execution function, you will get the value of the function first. Then assign a value to the can property, so what is done in this function? This function first prints obj, when obj has just been declared and has not been assigned yet, so an error is thrown when reading the next line obj.name for undefined,.


clipboard.png


< H2 > you want to achieve this, right? < / H2 >

closure

  var obj = function () {
        var name = 'js';

        var dofun = function () {

        };
        return can = (function () {
            // console.log(obj);
            return name;

        })();
    }
    console.log(obj(), '1');

class writing

class OBJ {
        constructor() {
            this.name = 'js';
        }

        can() {
            return this.name;
        }


        do() {


        }
    }
    var ob=new OBJ()

    console.log(ob.can(), '2');
Menu