[英]Parameters not being passed through two levels of JavaScript constructors
When running the below code I am receiving a type error when passing my arguments. 运行以下代码时,传递参数时收到类型错误。 It seems I am unable to pass my JSON data as arguments to the Employee object.
看来我无法将JSON数据作为参数传递给Employee对象。
This is the error I am receiving: 这是我收到的错误:
/home/ubuntu/test/tests/employee.js:4
this.name = params['name'] || "";
^
TypeError: Cannot read property 'name' of undefined
Below is the code: 下面是代码:
//comment
var Employee = function (params) {
this.name = params['name'] || "";
this.dept = params['dept'] || "general";
}
function Manager () {
this.reports = [];
}
Manager.prototype = new Employee;
function WorkerBee (params) {
console.log("params "+params);
this.base = Employee;
this.base(params);
// this.projects = params['projs'] || [];
}
WorkerBee.prototype = new Employee;
function Engineer (params) {
this.base = WorkerBee;
this.base(params);
params['projs']="engineering";
// this.base(params['name'], "engineering", params['projs']);
this.machine = params['mach'] || "";
}
Engineer.prototype = new WorkerBee;
var jane = new Engineer({'name': "Doe, Jane", 'projs':["navigator", "javascript"], 'mach':"belau"});
console.log(jane);
Any guidance would be appreciated to correct this example. 任何指导将被赞赏以纠正这个例子。
That's exactly why you should not create a new instance of the parent when you want to establish inheritance: If the constructor expects an argument, what do you pass? 这就是为什么要建立继承时不应该创建父对象的新实例的原因:如果构造函数需要一个参数,那么您要传递什么?
You should be using Object.create
instead: 您应该使用
Object.create
代替:
Child.prototype = Object.create(
Parent.prototype,
{constructor: {value: Child, configurable: true, writable: true}}
);
You also have to call the parent constructor as 您还必须调用父构造函数为
Parent.call(this, arg1, arg2, ...);
inside the child constructor. 在子构造函数中。 While
而
this.base = WorkerBee;
this.base(params);
does work, it's a bit unconventional. 确实有效,这有点不合常规。
More info in: Benefits of using `Object.create` for inheritance 更多信息,请参见: 使用Object.create进行继承的好处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.