內聲明(任何地方),並調用任何功能如下this
將是window對象
function anyFunc(){
alert(this); // window object
}
anyFunc();
var anyFunc2 = function(){
alert(this); // window object
}
anyFunc2();
如果你想創建私人活動和訪問「myObject的」的情況下,你可以按照下列方法的
一個
module = (function() {
var privateFunc = function() {
alert(this);
}
var myObject = {
publicMethod: function() {
privateFunc.apply(this); // or privateFunc.call(this);
}
};
return myObject;
}());
module.publicMethod();
兩個
module = (function() {
var _this; // proxy variable for instance
var privateFunc = function() {
alert(_this);
}
var myObject = {
publicMethod: function() {
privateFunc();
}
};
_this = myObject;
return myObject;
}());
module.publicMethod();
這些都是解決您的問題的方法。我會建議使用基於原型的對象。
編輯:
您可以使用第一種方法。
其實這裏myObject
是在相同的範圍內privateFunc
,你可以直接使用它的功能
var privateFunc = function() {
alert(myObject);
}
真正的情況是,你可以使用代理this
如下所示內。您也可以使用call
。
Module = function() {
var _this; // proxy variable for instance
var privateFunc = function() {
alert(this + "," + _this);
}
this.publicMethod = function() {
privateFunc(); // alerts [object Window],[object Object]
privateFunc.call(this); // alerts [object Object],[object Object]
}
_this = this;
return this;
};
var module = new Module();
module.publicMethod();
僅供參考:此變量與變量範圍無關。它只與該函數的調用上下文有關。它的值取決於* how *函數的調用方式。 – 2012-03-07 16:20:06
順便說一句,你可以''使用嚴格的''爲了使這種情況下的「this」是未定義的而不是窗口。它可以幫助很多有這種錯誤更明確地顯示。 – hugomg 2012-03-07 18:27:44