我正在研究在JavaScript中应用面向对象的方法。
我找到了一个使用继承的解决方案,我想知道是否有更好的方法以及如何包装我的类。
到目前为止,这就是我所做的。
People = function (name) {
this.name = name
this.age = null;
};
Employee = function (name) {
People.call(this, name);
this.IdentificationCode = null;
this.salary = null;
}
Jonh = new Employee("Jonh Smith");
Jonh.age = 25;
Jonh.IdentificationCode = 35632;
Jonh.salary = 3500;
注意:您不是从继承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());
现在,它会调用People
的getData
,将打印
[ 'Jonh Smith', 25 ]
注意:这种类型的继承通常称为原型继承。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句