2015-04-02 127 views
4

我將如何做到以下幾點:訪問父功能

var Parent = function() { 
this.Child = { 
    childFunction: function() { 
     this.parentFunction(); 
    } 
    }; 
    this.parentFunction = function() { 

    } 
}; 
var parentObj = new Parent(); 
parentObj.Child.childFunction(); 

在我得到「undefined是不是一個函數」,因爲很明顯parentFunction()不在範圍內的那一刻,但我我不確定使其無障礙的最佳方式是什麼?

回答

0
var Parent = function() { 
this.Child = { 
    childFunction: function() { 
     this.parentFunction(); 
    } 
    }; 
    this.parentFunction = function() { 

    } 
}; 

現在裏面的this.Child childFunction這將引用子對象,而不是父。

所以你必須使用self/that引用父。

var Parent = function() { 
    var that = this; 
    this.Child = { 

     childFunction: function() { 
      that.parentFunction(); 
     } 
     }; 
     this.parentFunction = function() { 

     } 
    }; 

您也可以使用Parent.parentFunction()。

var Parent = function() { 
    this.Child = { 

     childFunction: function() { 
      Parent.parentFunction(); 
     } 
     }; 
     this.parentFunction = function() { 

     } 
    }; 
1

thisChild將指Child對象不Parent從而在其中可以稍後在childFunction中使用的變量的存儲的Parentthis參考。

var Parent = function() { 
 
    var _self = this; //Store the reference 
 
    this.Child = { 
 
    childFunction: function() { 
 
     _self.parentFunction(); //Use here 
 
    } 
 
    }; 
 
    this.parentFunction = function() { 
 
    alert('In parentFunction'); 
 
    } 
 
}; 
 
var parentObj = new Parent(); 
 
parentObj.Child.childFunction();

0

的問題是,thischildFunction是指當前對象是Child

常見的解決方案是使用通過closure可用的變量訪問父項。例如:

var Parent = function() { 
    var _this = this; 

    this.Child = { 
     childFunction: function() { 
      _this.parentFunction(); 
     } 
    }; 

    this.parentFunction = function() { 
     // ... 
    } 
}; 

可替換地,一個更麻煩的方法是使用bind爲「領帶」的childFunction的函數上下文到當前this(其是親本):

childFunction: function() { 
    this.parentFunction(); 
}.bind(this); 

MDN