簡體   English   中英

為什么不能通過其原型訪問類中“ this”上的屬性?

[英]Why can’t I access a property on “this” in a class via its prototype?

我編寫了此類,並為此設置了一個數組屬性。 然后,我想向該數組添加一個項目。

但是,當我嘗試執行此操作時,出現錯誤“未捕獲的TypeError :無法讀取undefined屬性push ”。

這不可能嗎?

 class test { constructor() { this.myArray = []; } myMethod() { this.myArray.push("ok"); } }; console.log(test.prototype.myMethod()); 

那不是類的使用方式。 您需要先使用new test()實例化test 在您的情況下,從未調用過constructor ,因此從未定義this.myArray

這是唯一可行的方法:

let testInstance = new test();

testInstance.myMethod();

這樣,將調用constructor ,並且不會出錯。

當然,接下來,您將需要一些獲取數組的方法,以查看效果。

嘗試先創建實例。 查看我詳細評論過的代碼

test.prototype = { 
  constructor: test,
  myMethod: function() {
    this.myArray.push("ok");
  }
};

 var test = function(){ this.myArray = []; } test.prototype = { // add our custom constructor and custom methods constructor: test, myMethod: function() { this.myArray.push("ok"); } }; var myVar = new test(); // create new instance of test myVar.myMethod(); // run custom method to push val console.log( myVar.myArray ); 

您需要先啟動班級測試。

var t = new test();

供你參考:

console.log(test.prototype.myMethod()); 

將給您“未定義”。 嘗試例如:

var t = new test();
t.myMethod();
console.log(t.myArray);

獲得類似於以下內容的輸出:

Array [ "ok" ]

暫無
暫無

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

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