![](/img/trans.png)
[英]Why can't I access my JavaScript array by index outside of the d3 then function?
[英]Why can I not access my javascript constructors function from outside
這樣,我創建了我的對象:
var myViewModel = new MyViewModel("other");
為什么不能從視圖模型外部調用myViewModel.setHasOne(value)
?
我總是得到這個錯誤:
未捕獲的TypeError:無法調用未定義的方法'setHasOne'
我知道我可以直接設置屬性,但是我想知道如何使用方法?
這是我的功能:
function MyViewModel(other) {
var self = this;
self.other = other;
self.hasOne = false;
this.setHasOne= function (value) {
self.hasOne = value;
};
return this;
}
嘗試這個
function MyViewModel(other) {
var self = this;
this.other = other;
this.hasOne = false;
}
MyViewModel.prototype.setHasOne = function(value) {
this.hasOne = value;
};
注意:構造函數中不需要return
語句,因為您已經可以訪問this
。
您的代碼沒有任何問題,它應該可以工作,也許您在某個地方有錯字。 但是基於錯誤,問題不在於定義方法,而在於類的實例,該錯誤表明:
Uncaught TypeError: Cannot call method 'setHasOne' of undefined
這意味着無論出於何種原因,變量“ myViewModel”都未定義,因此無法為未定義的值找到“ setHasOne”。
關於您的代碼,請在名為“ Privileged Methods”的構造函數中定義方法。 這種方法的唯一好處是,它們可以訪問在構造函數內部定義的私有變量。 如果您不使用此功能,最好將您的方法定義為“公共方法”。 原因是,公共方法為類的每個實例使用共享存儲空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.