注:你是不是从People
继承,但你重用People
的构造函数。
建议1:
确保你没有创建全局变量。
var People = function (name) { // var at the beginning is important
...
...
var Employee = function (name) { // var at the beginning is important
...
...
var Jonh = new Employee("Jonh Smith");
建议2:
的构造函数应该有一个方法来初始化其他变量也是如此。
var People = function (name, age) {
this.name = name || null;
this.age = age || null;
};
var Employee = function (name, age, idCode, salary) {
People.call(this, name, age);
this.IdentificationCode = idCode || null;
this.salary = salary || null;
}
由于People
在其原型中没有任何方法,所以应该没问题。
但是,如果你有People
的原型方法,你希望他们能提供给您的派生对象还有,你能做到这一点
var People = function (name, age) {
this.name = name || null;
this.age = age || null;
};
People.prototype.getData = function() {
return [this.name, this.age];
};
现在定义Employee
这样
var Employee = function (name, age, idCode, salary) {
People.call(this, name, age);
this.IdentificationCode = idCode;
this.salary = salary;
}
// Make the Employee's prototype an object of parent class's prototype
Employee.prototype = Object.create(People.prototype);
然后做,
var Jonh = new Employee("Jonh Smith", 25, 35632, 3500);
console.log(Jonh.getData());
现在210
,它会调用People
的getData
并将打印
[ 'Jonh Smith', 25 ]
注:这种类型的继承通常被称为原型继承。
这个问题似乎是脱离主题,因为它是关于工作代码,它应该被迁移到http://codereview.stackexchange.com/ – Pavlo
调用部分运行实例特定部分的继承。您可以通过原型继承行为更多信息请阅读以下答案.http://stackoverflow.com/a/16063711/1641941 – HMR