簡體   English   中英

在類的方法范圍之外訪問`this`

[英]Access to `this` outside the scope of the method in class

我想知道為什么我無法在方法的裝飾器中訪問參數“ this.name”。

我的代碼:

 class A { name: string; construct() { this.name = 'test'; } @decorators(this.name) method() {} } 

在我的裝飾器中,我得到一個未定義。 我錯過了一些東西,我不明白。 你能幫我嗎? 謝謝

您從對象語法開始: var C = { name: string; } var C = { name: string; }我創建了一個片段你如何創建一個類,並使用擴展功能。 在評論中詢問ES5解釋。

 class A { constructor(param1, param2) { this.param1 = param1; this.param2 = param2; } // create a function get1() { return this.param1 } set1(param1) { this.param1 = param1; } } class B extends A { constructor(param1, param2, param3) { super(param1, param2); // Call A's constructor via super this.param3 = param3; } get3() { return this.param3 } set3(param3) { this.param3 = param3; } } let a = new A(10, "foo"), b = new B(5, "doo", "lala"); console.log("--- A ---"); console.log("a.get1() : " + a.get1()); // read date from a a.set1(3); // set a.param1 to 3 console.log("a.get1() : " + a.get1()); // read date from a console.log("a.param2 : " + a.param2); // read date from a a.param2 = 15; // set a.param2 to 15 console.log("a.param2 : " + a.param2); // read date from a // add a variable to the a object a.newvar = "new variable a"; console.log(a.newvar); // add a function to the a object a.newfunc = (param) => { return param; } console.log(a.newfunc("function a")); console.log("--- B ---"); console.log("b.get1() : " + b.get1()); // read date from b b.set1(3); // set b.param1 to 3 console.log("b.get1() : " + b.get1()); // read date from b console.log("b.param2 : " + b.param2); // read date from b b.param2 = 15; // set b.param2 to 15 console.log("b.param2 : " + b.param2); // read date from b console.log("b.get3() : " + b.get3()); // read date from b b.set3(3); // set b.param3 to 3 console.log("b.get3() : " + b.get3()); // read date from b // the newvar is not given with object b console.log(b.newvar); // add a variable to the b object b.newvar = "new variable b"; console.log(b.newvar); // add a function to the b object b.newfunc = (param) => { return param; } console.log(a.newfunc("function b")); 

暫無
暫無

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

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