2.7 This
Example 1.
var fullname = 'John Doe';
var obj = {
fullname: 'Colin Ihrig',
prop: {
fullname: 'Aurelio De Rosa',
getFullname: function() {
return this.fullname;
}
}
};
console.log(obj.prop.getFullname());
var test = obj.prop.getFullname;
console.log(test());
ANS:Aurelio De Rosa 和 John Doe 原因是,JavaScript中關鍵字this所引用的是函數上下文,取決於函數是如何調用的,而不是怎麼被定義的。 在第一個console.log(),getFullname()是作為obj.prop對象的函數被調用。因此,當前的上下文指代後者,並且函數返回這個對象的fullname屬性。相反,當getFullname()被賦值給test變量時,當前的上下文是全局對象window,這是因為test被隱式地作為全局對象的屬性。基於這一點,函數返回window的fullname,在本例中即為第一行代碼設置的。
Example 2.
var name = '全域';
var auntie = {
name: '漂亮阿姨',
callName: function() {
console.log(this.name);
},
};
(function() {
var a = auntie.callName;
a();
})();
ANS:全域
a = auntie.callName
函式間接參考,a()
為一般函式呼叫,因此 this
指向全域物件。
Example 3.
var myObject = {
foo: "bar",
func: function() {
var self = this;
console.log("outer func: this.foo = " + this.foo);
console.log("outer func: self.foo = " + self.foo);
(function() {
console.log("inner func: this.foo = " + this.foo);
console.log("inner func: self.foo = " + self.foo);
}());
}
};
myObject.func();
ANS:
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
在 outer 函式,this 和 self 都指向 myObject,因此輸出都是 bar,但在 inner 函式,由於 IIFE 有自己的作用域,因此 this 輸出為 undefined,但是 self 因為保存了 this 的指向,因此輸出為 bar
Last updated
Was this helpful?