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
实例都从A
inheritance它:
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