gpt4 book ai didi

Javascript - parent.call(arguments) 和 child.prototype = new parent(arguments) 之间的区别?

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

我正努力让自己的头脑完全围绕原型(prototype)继承和 Javascript 的继承系统。

我试图找出这两个示例之间的区别。我猜它与原型(prototype)继承链有关,但我找不到与这两者相关的信息。

示例 1 - 调用()

function Vehicle(wheels) {
this.wheels = wheels;
}

function Car(doors) {
this.doors = doors;
Vehicle.call(this,4);
}

示例 2 - 原型(prototype)

function Vehicle(wheels) {
this.wheels = wheels;
}

function Car(doors) {
this.doors = doors;
}
Car.prototype = new Vehicle(4);

最佳答案

在第一个示例中,您正在初始化 Car 对象,使其具有新的 Vehicle 对象的所有相同属性。然而,它不是“真正的”继承,有以下几种方式:

var car = new Car(2);
car instanceof Vehicle; // => false

这是第一件事:instanceof 将不起作用。这是第二个:

var car = new Car(2);

Vehicle.prototype.drive = function() {
console.log('vroom!');
};

car.drive(); // throws

所以这是第二件事:对 Car 实例的访问不会向上到达原型(prototype)链到 Vehicle 的原型(prototype)。

考虑到这一点,我倾向于支持第二种方法。


也就是说,您可能实际上想要两者,因为您的Vehicle 构造函数中可能有每个实例的初始化逻辑,您实际上想要在你初始化一个 Car 时执行(这不会仅仅通过设置原型(prototype)来实现)。

要理解我的意思:在您的示例中,您总是将 4 作为 wheels 参数传递给 Vehicle 构造函数,这使得感觉。但是假设我们添加另一个参数,该参数可能因实例而异:

function Vehicle(wheels, color) {
this.wheels = wheels;
this.color = color;
}

现在我们可以采用两种方法:

function Car(doors, color) {
this.doors = doors;
Vehicle.call(this, 4, color);
}

Car.prototype = new Vehicle();

请注意,在设置 Car 的原型(prototype)时,我们没有将任何内容传递给 Vehicle 构造函数,而是在 Car 中显式调用构造函数.这样我们就可以正确设置 color

另一种方法是:

function Car(doors, color) {
this.doors = doors;
this.color = color;
}

Car.prototype = new Vehicle(4, null);

那也行。

关于Javascript - parent.call(arguments) 和 child.prototype = new parent(arguments) 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21757833/

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