我正在学习如何在javascript中继承。我跟着this example。解释原型链。我创建了一个更详细的示例,显示了3个级别Person > Employee > Engineer
我的例子的不同之处在于创建了Employee
的实例,传递了参数。但是,如果我按照上面提到的mozilla示例,我需要将其传递给Child原型:
var Engineer.prototype = new(Employee);
我没有传递任何论据。
之后,当我将Engineer.prototype
内容打印到控制台时,我确实看到了该物业"公司" as" undefined"。
Engineer prototype { _alive: true,
_company: undefined,
_title: null,
constructor: [Function] }
Drew instance: { _alive: true,
_company: 'Apple',
_title: null,
_specialization: 'tester' }
我确定可以忍受这个,但它看起来并不干净整洁。
这里的问题是什么是最佳做法? Shell我宁愿不将任何参数传递给构造函数并创建一些init方法并显式调用它或shell我忽略构造函数中的未定义属性?
这是我的例子中的代码:
var Person = function(){
this._alive = true;
};
var Employee = function(company){
Person.call(this);
this._company = company;
this._title = null;
}
Person.prototype.die = function(){
this._alive = false;
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.prototype.setTitle = function(newtitle){
this._title = newtitle;
}
Employee.prototype.title = function(){
return this._title;
}
Employee.prototype.company = function(){
return this._company;
}
var Engineer = function(company, specialization){
Employee.call(this,company);
this._specialization = specialization;
}
Engineer.prototype = new(Employee);
Engineer.prototype.constructor = Engineer;
var drew = new(Engineer)('Apple','tester');
console.log('Engineer prototype', Engineer.prototype);
console.log('Drew instance: ',drew);