JavaScript中的this关键字使用详解(2)

var myObject = { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' }; var secondObject = { myName : 'Colin' }; myObject.sayHello(); // logs 'Hi! My name is Rebecca' myObject.sayHello.call(secondObject); // logs 'Hi! My name is Colin'

函数被 Function.call 调用过的例子:

var myName = 'the global object', sayHello = function () { console.log('Hi! My name is ' + this.myName); }, myObject = { myName : 'Rebecca' }; var myObjectHello = sayHello.bind(myObject); sayHello(); // logs 'Hi! My name is the global object' myObjectHello(); // logs 'Hi! My name is Rebecca'

函数被对象调用的例子:

var myName = 'the global object', sayHello = function() { console.log('Hi! My name is ' + this.myName); }, myObject = { myName : 'Rebecca' }, secondObject = { myName : 'Colin' }; myObject.sayHello = sayHello; secondObject.sayHello = sayHello; sayHello(); // logs 'Hi! My name is the global object' myObject.sayHello(); // logs 'Hi! My name is Rebecca' secondObject.sayHello(); // logs 'Hi! My name is Colin'

在调用一个很深的命名空间中函数的时候,我们通常会缓存一个变量指向那个要调用的函数,以减少代码量。但是这样做会改变函数中 this 的值,最终执行错误的操作。例如:

var myNamespace = { myObject : { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' } }; var hello = myNamespace.myObject.sayHello; hello(); // logs 'Hi! My name is undefined'

所以,要缓存变量以节省代码量的话,正确的做法是只节省到调用那个函数的对象为止:

var myNamespace = { myObject : { sayHello : function() { console.log('Hi! My name is ' + this.myName); }, myName : 'Rebecca' } }; var obj = myNamespace.myObject; obj.sayHello(); // logs 'Hi! My name is Rebecca'

总之,有一个大原则:谁调用了那个函数,this 就指向谁。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wggsgx.html