JS beginners are always confused by the this keyword because it’s a bit tricky in JS compared to other modern programming languages. “This” is usually the current object, but things don’t happen as they should. The this keyword in JS is determined by the caller of the function, who calls this refers to which. If the caller is not found, this points to the Windows object.

Have some corn

The first example is simple. Calls func() in the test object, so the ‘this’ in func() points to the test object, so the printed prop is the test prop, which is 42.

var test = {
 prop: 42,
func: function() {returnthis.prop; }}; console.log (test.func()); / / 42Copy the code

If we call getFullname directly, the second example will print out ‘David Jones’, because this cannot find the caller, so the default is the window object, and the fullname printed is global.

Var fullname = 'David Jones' var obj ={fullname:' Colin Brown ', prop:{fullname: 'Aurelio Deftch', getFullname:function() {return this.fullname;
        }
    }
}
var test = obj.prop.getFullname
console.log(test()) // David Jones obj.prop. GetFullname () // 'Aurelio Deftch'Copy the code