[英]Parameters not being passed through two levels of JavaScript constructors
运行以下代码时,传递参数时收到类型错误。 看来我无法将JSON数据作为参数传递给Employee对象。
这是我收到的错误:
/home/ubuntu/test/tests/employee.js:4
this.name = params['name'] || "";
^
TypeError: Cannot read property 'name' of undefined
下面是代码:
//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);
任何指导将被赞赏以纠正这个例子。
这就是为什么要建立继承时不应该创建父对象的新实例的原因:如果构造函数需要一个参数,那么您要传递什么?
您应该使用Object.create
代替:
Child.prototype = Object.create(
Parent.prototype,
{constructor: {value: Child, configurable: true, writable: true}}
);
您还必须调用父构造函数为
Parent.call(this, arg1, arg2, ...);
在子构造函数中。 而
this.base = WorkerBee;
this.base(params);
确实有效,这有点不合常规。
更多信息,请参见: 使用Object.create进行继承的好处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.