Why does the value of “this” changes.?

前端 未结 2 1330
天命终不由人
天命终不由人 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);
    

提交回复
热议问题