this由調用函數決定。 (也就是函數的調用方式)請參閱我的其他answers以獲取更多details。
var myObject = {
name: 'Tyrion',
alias: 'imp',
_self: function() {
return this;
},
// I know this context is fine, but let's pretend it's being called from elsewhere.
getAlias: function() {
var _self = myObject._self();
return _self.alias;
}
};
//member invocation
console.log(myObject._self() === myObject); // true
var aFucntion = myObject._self;
//functional invocation
console.log(aFucntion() === myObject); // false
console.log(aFucntion() === this); //true
相反擔心的this上下文,一個解決方法是將分配到this在外部函數的值,然後訪問在內部函數值。這就是所謂的封閉
var MyObject = function (title) {
var _self = this,
helper = function() {
return _self.title + " " + _self.name;
};
this.title = title;
this.fullName = function() {
return helper(); //functional invocation
//if helper used this, this would be global
};
this.name = 'Tyrion';
this.alias = 'imp';
this.getAlias = function() {
//access to _self through closure
return _self.alias;
};
};
//constructor invocation
var aObject = new MyObject("Mr.");
console.log(aObject.getAlias()); //imp
console.log(aObject.fullName()); //Mr. Tyrion
FYI:
如果_self返回myObject的,上下文不會母校。
_self: function() {
return myObject;
}
在你的上下文中'this'''''可能是'window'',這不是'this'的作用。'this'在函數中有意義,上下文取決於你如何調用函數。這裏沒有功能......你有沒有嘗試在'getAlias'裏面使用'this' – elclanrs
編輯之後,我沒有看到那個抽象的點......每個函數頂部的'var self = this'都更短比'var self = myObject.self()',沒有必要那個IMO,除非我錯過了這一點...... – elclanrs
我知道這個例子很好,但是想象一下getAlias是從其他上下文中調用的。 –