![](/img/trans.png)
[英]JavaScript: how to call a function on the prototype property, from inside another function on the prototype property, all inside a closure?
[英]How to call a prototype function inside another prototype function without losing context
我有這個代碼 :
var MyObj = (function() {
//Constructor
var MyObj= function(){
this.myArray = [1,2,3];
}
MyObj.prototype = {
myFunc: function(){
alert(this.myArray.toString());
},
myFuncCaller: function(){
MyObj.prototype.myFunc();
}
};
return MyObj;
})();
var myObj = new MyObj();
myObj.myFunc();
//This line will throw an exception because this.myArray is undefined
myObj.myFuncCaller();
為什么this.myArray
未定義? 我知道我做錯了什么,怎么做才是正確的方法?
只需使用this
:
this.myFunc();
當您使用Javascript調用函數時, this
函數將設置為您調用它的表達式。
例如,在您的代碼中, myFunc()
this
是MyObj.prototype
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.