参数未通过两级JavaScript构造函数传递

时间:2014-09-03 23:33:13

标签: javascript oop object inheritance hierarchy

运行以下代码时,我在传递参数时收到类型错误。似乎我无法将我的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);

任何指导都将不胜感激,以纠正这个例子。

1 个答案:

答案 0 :(得分:1)

这就是为什么你不想在建立继承时创建父实例的原因:如果构造函数需要参数,你传递了什么?

您应该使用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);

确实有效,它有点不同寻常。


更多信息:Benefits of using `Object.create` for inheritance