ES6 JS类中的属性inheritance

/A.js有以下代码;

 class A { constructor(token) { this.token = token; } lok() { return 'hello'; } } module.exports = A 

/dir1/dir2/B.js有以下代码;

 let A = require(__dirname + '/../../A.js') class B extends A { constructor(token) { super(token) } tok() { return this.token; } } module.exports = B 

问题是,我如何从类Ainheritance令牌属性,

 let init = new A('123') init.tok() //will return token 

相反,我的问题是,如何从基类(A)inheritance在构造函数中声明的属性,以便我可以在子类(B)中使用它们。

当执行let init = new A('123') ,您正在创buildA类的一个实例。 这意味着init只具有A类的属性和方法,值得注意的是, init没有在B声明的tok方法。

如果您执行let init = new B('123') ,您将创buildB类的一个实例,它也inheritance了A类的属性。

B的构造函数中的super(token)意味着A的构造函数使用参数token调用,因此您设置this.token = token 。 然后,您可以采取您的B实例init并成功地呼吁:

 let init = new B('123') init.tok() // '123' 

你也可以在这个init调用lok ,因为任何B实例都从Ainheritance它:

 init.lok() // 'hello' 

你的问题更多的是因为typesA任何对象都没有 tok()方法,因为它只在B类中。 虽然A具有token属性,但它不具有使用该方法检索它的function。 例如,你可以这样做:

 let init = new A('123') // init.tok() // this will never work as the method only exists on `B` objects console.log( .init.token ); // this will work fine because you add the property in the constructor