首页 >web前端 >js教程 >JavaScript 原型继承中'new”的作用是什么:'Derived.prototype = new Base”?

JavaScript 原型继承中'new”的作用是什么:'Derived.prototype = new Base”?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-24 09:46:20696浏览

What is the Role of `new` in JavaScript Prototypal Inheritance: `Derived.prototype = new Base`?

理解“Derived.prototype = new Base”中“new”的作用

考虑以下代码片段:

WeatherWidget.prototype = new Widget;

其中Widget 代表一个构造函数,我们的目标是使用名为 WeatherWidget 的新函数来扩展它。问题出现了:new 关键字在这种情况下的意义是什么?如果省略它会产生什么后果?

'new' 的作用

new 关键字执行关键操作通过将 Widget 实例化为构造函数并将其返回值分配给 WeatherWidget 的原型属性。如果不存在 new 关键字,则在不提供参数的情况下调用 Widget(例如,通过省略括号)将导致未定义的行为。此外,如果 Widget 的实现未设计为作为构造函数调用,则此方法可能会无意中污染全局命名空间。

继承的实例行为

通过使用所示的 new 关键字,所有实例WeatherWidget 将从同一个 Widget 实例继承,从而产生以下原型链:

[new WeatherWidget()] → [new Widget()] → [Widget.prototype] → …

这种特殊的安排可能适合以下情况:所有 WeatherWidget 实例都旨在共享从 Widget 实例继承的属性值。然而,在大多数情况下,这种共享继承是不可取的。

正确的基于类的继承

为了在使用原型的 JavaScript 中有效地实现基于类的继承,建议使用以下方法:

function Dummy () {}
Dummy.prototype = Widget.prototype;
WeatherWidget.prototype = new Dummy();
WeatherWidget.prototype.constructor = WeatherWidget;

该技术确保 WeatherWidget 实例通过原型链正确继承属性,但不会在实例之间共享属性值,因为它们从中间虚拟构造函数。这是生成的原型链:

[new WeatherWidget()] → [new Dummy()] → [Widget.prototype] → …

利用现代 JavaScript 功能

在遵循 ECMAScript 5 及更高版本的现代 JavaScript 实现中,首选以下方法:

WeatherWidget.prototype = Object.create(Widget.prototype, {
  constructor: {value: WeatherWidget}
});

这种方法的另一个好处是创建不可枚举、不可配置的构造函数

调用父构造函数

最后,需要注意的是,父构造函数(在本例中为 Widget)只会从子构造函数(WeatherWidget)中显式调用,类似如何使用 apply 或 call 方法:

function WeatherWidget (…)
{
  Widget.apply(this, arguments);
}

以上是JavaScript 原型继承中'new”的作用是什么:'Derived.prototype = new Base”?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn