在扩展类中运行构造函数
Run the constructor function in extended class
我在Node.js中玩extends
。我创建了一个名为Person
的类和另一个扩展了Person
的类,称为Worker
。Worker
类有一个工作良好的work
函数(它显示了Person
中定义的getName()
结果)。我想为Worker
构造函数添加另一个参数。
我尝试在Worker
中添加constructor
函数,如下所示:
"use strict";
class Person {
constructor (name) {
this.name = name;
}
getName () {
return this.name;
}
}
class Worker extends Person {
// Without this constructor, everything works correctly
// But I want to add the type field
constructor (name, type) {
console.log(1);
// this.type = type;
}
work () {
console.log(this.getName() + " is working.");
}
}
var w = new Worker("Johnny", "builder");
w.work();
当运行这个时,我得到以下错误:
path/to/my/index.js:14
console.log(1);
^
ReferenceError: this is not defined
at Worker (/path/to/my/index.js:14:17)
at Object.<anonymous> (/path/to/my/index.js:22:9)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
为什么会出现这种情况?此外,我该如何正确地执行此操作?
我想在w
实例中访问type
字段:
console.log(w.type);
您需要在扩展构造函数中调用super()
。如果没有这一点,它就不会调用Person
类中的构造函数。
class Person {
constructor (name) {
this.name = name;
}
getName () {
return this.name;
}
}
class Worker extends Person {
constructor (name, type) {
super(name);
this.type = type;
}
work () {
console.log(this.getName() + " is working.");
}
}
以下内容现在应该起作用:
var w = new Worker("Johnny", "builder");
w.work();
console.log(w.type); //builder
相关文章:
- ES6构造函数返回基类的实例
- 使用Google Visualization动态调用构造函数
- javascript中对象构造函数中的var属性与this.properties
- 理解typescript中的构造函数接口
- 为什么构造函数不是构造函数
- 如果在构造函数中有“返回”,则在 JavaScript 中的新运算符中做了什么
- 未能运行构造函数:TypeError:对象#<对象>没有方法'addPlugin'
- 属性在我的自定义构造函数中无法正常运行 - Javascript
- 如何在运行时访问typescript类公共属性(调试)?只有构造函数和函数是可访问的
- 这个对象构造函数阻止我的脚本运行
- 在构造函数之后运行其他操作
- 继承构造逻辑,但在创建 Sub 对象时运行超级构造函数
- JS构造函数的运行顺序
- 原型链接、调用父方法的行为就像父构造函数从未运行过一样
- 在扩展类中运行构造函数
- 继承:构造函数不运行'
- MobX -运行一个存储的构造函数在另一个
- Js es6类的构造函数运行前先实例化构造函数
- Javascript:如何在覆盖子类中的继承方法后运行父类的构造函数逻辑
- 构造函数:其中“公共”属性在运行时位于内存中