JavaScript 中的面向对象继承



我正在研究在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());

现在,它将调用PeoplegetData并将打印

[ 'Jonh Smith', 25 ]

注意:这种类型的继承通常称为原型继承。

function Person(name, age) {
    this.name = name;
    this.age = age;
}

function Employee(name, age) {
    Person.call(this, name, age);
    this.salary = null;
}

Employee.prototype = Object.create(Person.prototype);
var teste = new Employee("Felipe",25)
teste instanceof Employee // true
teste instanceof Person // true

Object.create正在创造遗产。Object.create 接收一个对象并返回另一个对象,其原型是传递的对象。

您可以使用 Object.createEmployee设置为从People继承。

var People = function (name) {
    this.name = name
    this.age = null;
};
var Employee = function (name) {
    People.call(this, name);
    this.IdentificationCode = null;
    this.salary = null;
}
Employee.prototype = Object.create(People.prototype); // create a new object inheriting from People.prototype
Employee.prototype.constructor = Employee; // put the constructor back
var Jonh = new Employee("Jonh Smith");
Jonh.age = 25;
Jonh.IdentificationCode = 35632;
Jonh.salary = 3500;

您可以通过多种方式做到这一点。一个和你一样。另一种是使用原型对象:

Employee.prototype = new People();

您还可以使用返回新创建对象的函数,并从另一个对象调用一个:

function getPeople ( name ) {
    var result;
    result.name = name;
    result.age = null;
    return result;
}
function getEmployee ( name ) {
    var result = getPeople ( name );
    result.IdentificationCode = null;
    result.salary = null;
    return result;
}

最新更新