JavaScript中的原型继承惯例 [英] Convention for prototype inheritance in JavaScript

查看:108
本文介绍了JavaScript中的原型继承惯例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多这样的代码:

I see a lot of code like this:

function Base() {}
function Sub() {}
Sub.prototype = new Base();

但是,如果你这样做:

s = new Sub();
print(s.constructor == Sub);

这是假的。这对我来说似乎很困惑,因为s的构造函数确实是Sub。执行此操作是常规/更好吗?

This is false. This seems confusing to me, since s's constructor is, indeed, Sub. Is it conventional/better to do this?

function Base() {}
function Sub() {}
Sub.prototype = new Base();
Sub.prototype.constructor = Sub;

还是不重要?

推荐答案

'构造函数'不会像它看起来那样做。除了它的非标准之外,这是避免使用它的一个很好的理由 - 坚持使用instanceof和prototype。

'constructor' doesn't do what it looks like it does. This, in addition to its non-standardness, is a good reason to avoid using it - stick with instanceof and prototype.

技术上:'构造函数'不属于's'实例,它是'Sub'原型对象的一个​​属性。当您在Mozilla中创建Sub函数时,您将获得一个新创建的默认Sub.prototype对象,该对象具有指向Sub函数的构造函数作为礼貌。

Technically: 'constructor' is not a property of the 's' instance, it is a property of the 'Sub' prototype object showing through. When you create the 'Sub' function in Mozilla, you get a newly-minted default Sub.prototype object which has a 'constructor' pointing back to the Sub function as a courtesy.

但是,然后用新的Base()替换该原型。返回Sub的原始默认原型丢失了;相反,Sub.prototype是Base的一个实例,没有任何重写的'constructor'属性。所以:

However you then replace that prototype with a new Base(). The original default prototype with the link back to Sub is lost; instead, Sub.prototype is an instance of Base without any overriding 'constructor' property. So:

new Sub().constructor===
Sub.prototype.constructor===
new Base().constructor===
Base.prototype.constructor===
Base

...一直到最基本的对象,你原型没有改变。

...all the way down to the most basic object whose prototype you didn't change.


是吗传统/更好地做到这一点?

Is it conventional/better to do this?

当处理JavaScript对象/类时,没有一个约定;每个库的元类系统的行为略有不同。我还没有看到一个手动为每个派生类编写'构造函数'的人,但是如果你真的想要真正的构造函数,它似乎是一个很好的解决方案;它还会使代码与不提供构造函数的浏览器/引擎兼容。

When dealing with JavaScript objects/classes there is no one convention; every library's metaclass system behaves slightly differently. I haven't seen one that writes 'constructor' to each derived class manually, but it seems as good a solution as any if you really want to have the real constructor available; it will also make the code compatible with browsers/engines that don't give you 'constructor'.

我会考虑给它一个不同的名称,以避免与现有的和不同行为的构造函数属性混淆。

I'd consider giving it a different name, though, to avoid confusion with the existing and differently-behaving 'constructor' property.

这篇关于JavaScript中的原型继承惯例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆