这个为什么提示NaN?

为什么没有输出2

class People {
    static homeland = 1;
    test() {
        this.homeland += 1
        console.log(this.homeland);
    }
}



let a = new People()
a.test()
阅读 1.6k
3 个回答

People.homeland // 类上才有 homeland

new People().homelnad // undefined // 实例没有 homeland

undefined + 1 // NaN

class People {
    homeland = 1; // 这需要你配 babel 吧
    test() {
        this.homeland += 1
        console.log(this.homeland);
    }
}

let a = new People()
a.test()
class People {
    static homeland = 1; // 这需要你配 babel 吧
    test() {
        People.homeland += 1
        console.log(People.homeland);
    }
}

let a = new People()
a.test()

不知道你想怎么用

你好,在 ES6 Class 语法中通过 static 声明的是静态方法或属性,其不能在类的实例上调用,而只能通过类本身调用。上例中你只能通过 People.homeland 获取 static homeland 的值。(关于 Class static 方法的具体用法,你可以参考 MDN文档 Class static。)

如果你想声明实例上的属性,直接声明在 Class 内部即可:

class People {
  homeland = 1
  test() {
    this.homeland += 1;
    console.log(this.homeland);
  }
}

let a = new People();
a.test(); // 2

希望这个回答能够对你有所帮助!

类的静态属性是绑定到类中,由类共有,不能被实例化为实例属性。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题