A question about the understanding of this in Javascript?

see this piece of code, as follows:

function foo() {      
     console.log( this.a ); 
} 
 
var obj2 = {      
    a: 42,     
    foo: foo  
}; 
 
var obj1 = {      
    a: 2,     
    obj2: obj2  
}; 
 
obj1.obj2.foo(); //42

how should I understand this code?
as I understand it, obj2 should end up with:

var obj2 = {      
    a: 42,     
    foo: function () {      
        console.log( this.a ); 
    }   
};
var obj1 = {      
    a: 2,     
    foo: {      
        a: 42,     
        obj2: function () {      
            console.log( this.a ); 
        }   
    }  
};

if this is the case, I really don"t understand the chain writing of obj1.obj2.foo (); .
also hopes to give me some advice. Thank you!

Nov.09,2021

var obj1 = {      
    a: 2,     
    obj2: {      
        a: 42,     
        foo: function () {      
            console.log( this.a ); 
        }   
    }  
}; 

this is not a chained call, it's just a simple object property.


this is easy to understand, that is, one object contains another object
, but not all the calls to attributes within the object are. This is true of
js. The same is true of php.
$obj1- > obj2- > fun ();. The result is to call a function of the obj2 object stored in obj1


.
var obj1 = {      
    a: 2,     
    obj2: {      
        a: 42,     
        foo: function () {      
            console.log( this.a ); 
        }   
    }  
};

obj1.obj2.foo (); is an attribute access expression, which belongs to the method call, that is, the foo () method of calling obj1.obj2. Obj1.obj2 is the calling context, and the final output value is naturally 42.


Brother, if you can't identify the this problem next time, that's what you think. The this points to whoever comes first, except for some that are called by window.

Menu