gpt4 book ai didi

javascript - 了解 Javascript 构造函数 : custom create method

转载 作者:行者123 更新时间:2023-11-30 10:35:44 25 4
gpt4 key购买 nike

我正在尝试更好地理解 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;

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

更新

如果 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;

关于javascript - 了解 Javascript 构造函数 : custom create method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14129867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com