理解Javascript构造函数:自定义create方法

Understanding Javascript constructors: custom create method

本文关键字:create 方法 自定义 Javascript 构造函数 理解      更新时间:2023-09-26

我试图更好地理解Javascript中的OOP。有人能解释一下在下面的例子中如何使用create方法和替代方法吗?我在网上查了一下,看了几篇关于SO的文章,仍然没有完全掌握下面代码中发生了什么。我提供了一些评论来说明我的理解。请纠正我的错误。

这个例子用于覆盖基类中的方法:

// Defines an Employee Class
function Employee() {}
// Adds a PayEmployee method to Employee
Employee.prototype.PayEmployee = function() {
    alert('Hi there!');
}
// Defines a Consultant Class and
// Invokes the Employee Class and assigns Consultant to 'this' -- not sure and not sure why
// I believe this is a way to inherit from Employee?
function Consultant() {
    Employee.call(this);
}
// Assigns the Consultant Class its own Constructor for future use -- not sure
Consultant.prototype.constructor = Consultant.create;
// Overrides the PayEmployee method for future use of Consultant Class
Consultant.prototype.PayEmployee = function() {
    alert('Pay Consultant');
}

代码:

function Consultant() {
    Employee.call(this);
}

在调用Consultant构造函数时调用Employee构造函数(即,在创建Consultant实例时)。如果Employee构造函数正在进行任何类型的初始化,那么在创建顾问"子类型"时调用它将是很重要的。

这个代码:

Consultant.prototype.constructor = Consultant.create;

有点神秘。它暗示有一个名为create的函数,它是Consultant函数对象的属性。但是,在您发布的代码示例中,没有这样的属性。实际上,这一行是将undefined赋值给Consultant构造函数。

你的问题没有问,但只是供参考,我认为你可能想要的是而不是那行与create函数,是这样的:

Consultant.prototype = new Employee();
Consultant.prototype.constructor = Consultant;

这是原型继承模式。这当然不是唯一或最好的方法,但我喜欢它。

如果Employee接受一个参数,你可以这样处理:

// Employee constructor
function Employee(name) {
    // Note, name might be undefined. Don't assume otherwise.
    this.name = name;
}
// Consultant constructor
function Consultant(name) {
    Employee.call(this, name);
}
// Consultant inherits all of the Employee object's methods.
Consultant.prototype = new Employee();
Consultant.prototype.constructor = Consultant;