简体   繁体   English

类定义的首选JavaScript惯用法

[英]Preferred JavaScript Idiom for class definition

What is the preferred idiom for defining a class in JavaScript? 在JavaScript中定义类的首选惯用法是什么? I could define a constructor function for complex numbers as follows: 我可以为复数定义一个构造函数 ,如下所示:

function Complex(real, imag) {
    this.real = real;
    this.imag = imag || 0.0;
    this.add = function(other) {
        this.real += other.real;
        this.imag += other.imag;
        return this;
    }
}

or I could do the following: 或者我可以执行以下操作:

function Complex(real, imag) {
    this.real = real;
    this.imag = imag || 0.0;
}

Complex.prototype = {
    add : function(other) {
        this.real += other.real;
        this.imag += other.imag;
        return this;
    }
}

Since neither textbook JavaScript : The Good Parts nor JavaScript The Definitive Guide define classes the first way I suspect these are not equivalent -- I suspect I need use prototype if I plan on using inheritance. 由于教科书的《 JavaScript:The Good Parts》和《 JavaScript权威指南》没有定义类的第一种方式,我怀疑它们并不等效-我怀疑如果计划使用继承,则需要使用prototype This seems a little murky to me -- can anyone clarify this? 在我看来,这有点模糊-有人可以澄清吗?

I know I could use the Object.create() method suggested in the aforementioned texts and do things the prototypical way, but I don't see folks doing this in practice much. 我知道我可以使用前面提到的文本中建议的Object.create()方法,并以原型方式进行操作,但是我看不到人们在实践中做得太多。

In the first example, every new object get's its own copy of the add() method. 在第一个示例中,每个新对象都具有其自己的add()方法的副本。

In the second example, every new object share's a single copy of the add() function via the prototype . 在第二个示例中,每个新对象都通过prototype共享add()函数的单个副本。

Obviously the latter is more efficient. 显然后者更为有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM