簡體   English   中英

如何在不丟失上下文的情況下在另一個原型函數中調用原型函數

[英]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() thisMyObj.prototype

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM