簡體   English   中英

函數內部的javascript類變量表示未定義的ES6

[英]javascript class variable inside function says undefined ES6

class Auto {
  printauto() {
    var type = "2 wheeler";
    var color = "green";
    console.log("Car type is="+this.type+" "+" and color="+this.color);
 }
}

var a = new Auto();
a.printauto();

為什么輸出未定義?

汽車類型=未定義且顏色=未定義

僅通過聲明將變量附加到類上下文不會發生。 你必須明確:

 class Auto { printauto() { this.type = "2 wheeler"; // explicitly attach to `this` this.color = "green"; // same here console.log("Car type is="+this.type+" "+" and color="+this.color); } } new Auto().printauto(); 

構造函數通常是進行此類初始化的最佳位置:

 class Auto { constructor() { this.type = "2 wheeler"; // explicitly attach to `this` this.color = "green"; // same here } printauto() { console.log("Car type is="+this.type+" "+" and color="+this.color); } } new Auto().printauto(); 

這是指類,您沒有在類中聲明顏色和類型。 顏色並在您的printauto方法范圍內。 要么在課堂上宣布它們,要么就是這樣做

console.log("Car type is="+type+" "+" and color="+color);

通過在課堂上宣布

class Auto {
    this.type = "2 wheeler";
    this.color = "green";

    printauto() {
        console.log("Car type is=" + this.type + " " + " and color=" + this.color);
    }
}
var a = new Auto();
a.printauto();

正如Felix King在評論中所描述的,變量aAuto類的屬性不同

 class Auto { printauto() { var type = "2 wheeler"; var color = "green"; console.log("Car type is="+ type+" "+" and color="+color); } } var a = new Auto(); a.printauto(); 

暫無
暫無

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

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