subclass.prototype = new superclass()vs. subclass = new superclass() [英] subclass.prototype = new superclass() vs. subclass = new superclass()

查看:86
本文介绍了subclass.prototype = new superclass()vs. subclass = new superclass()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用javascript实例化子类

I've been instantiating subclasses in javascript using

object = new class ()

但我注意到有些人使用

object.prototype = new class ()

问题:有什么区别?对我来说,似乎后者更多地尊重继承链,因为如果 class()有一堆 this.variable = x 语句和对象是你想从它继承而不是类的实例,你准确地将这些变量分配给对象的原型而不是像前一种情况那样分配给对象本身。所以实际上它是这样的?

Question: What's the difference? To me it seems like the latter is respecting the inheritance chain more because if class () has a bunch of "this.variable = x" statements, and object is something you want to inherit from it rather than an instance of class, you are accurately assigning those variables to object's prototype rather than to the object itself as in the former case. So in effect it's like this?

object = new class () |vs.| subclass.prototype = new superclass ()

但是,程序中的功能都是相同的?

附带问题:我还有点不清楚运算符究竟是什么确实。在我看来,只需创建一个空对象并分配它的 proto 属性?

Side question: Also I'm a bit unclear as to what the new operator actually does. It seems to me to do something like just create an empty object and assign it's proto property?

推荐答案

不同的是,当你这样做时:

The difference is that when you do:

var subclass = new superclass();

您正在创建超类的实例。 子类只是变量。您没有创建子类(即,使子类继承超类)。
在后一个例子中,假设子类是一个函数,你说所有子类的新实例都应该继承(即。子类) superclass

you are creating an instance of superclass. subclass is just variable. You are not creating a sub-class (ie. making subclass inherit superclass). In the latter example, assuming subclass is a function, you are saying that all new instances of subclass should inherit (ie. sub-class) superclass.

所以:

function superclass() {this.stuff="stuff";}
function subclass() {}
subclass.prototype = new superclass();
alert(new subclass().this); // pops up "stuff"

是典型的继承。

对于 new 运算符,它用于创建内置对象和用户定义类型的实例。用户定义的类型只是一个函数。

As for the new operator, it is used for creating an instance of built-in objects and user defined types. A user defined type is simply a function.

编辑:
当我在上面写道时,子类继承了使用原型继承的超类型,我的意思是所有子类的新实例都继承自一个特定实例的超类,而不是来自超类类型/函数本身。

When I wrote above that subclass inherits supertype using prototypical inheritance, I mean that all new instances of subclass inherit from one particular instance of superclass, not from the superclass type/function itself.

这篇关于subclass.prototype = new superclass()vs. subclass = new superclass()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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