Why does the value of “this” changes.?

前端 未结 2 1327
天命终不由人
天命终不由人 2020-12-11 04:12

I am learning javascript and i came across a doubt. Why is the value of \"this\" undefined in the first example , but prints out correctly in the second.

example 1:<

相关标签:
2条回答
  • 2020-12-11 04:44

    In the first case, the implicit this object is the global scope. Because there is no myName in the global scope, you get undefined.

    If you want a free function with the proper this, use bind:

    var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject);
    
    0 讨论(0)
  • 2020-12-11 05:00

    First case you are just getting the reference of the function to the vairable hello, and invoking it from global context (window in browsers, global in node), So this becomes what invoked the function except for (bound functions). You can always set the context explicitly using function.call or set the context explicitly to the function using Ecma5 function.bind

    hello.call(myNamespace.myObject); //now you are setting the context explicitly during the function call.
    

    or just bind it while getting the function reference.

    var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject); //Now no matter where you call it from `this` will point to the context of myObject
    

    Second case you are invoking it from the object itself so this points to the object.

    0 讨论(0)
提交回复
热议问题