用于类定义的首选JavaScript习语

Preferred JavaScript Idiom for class definition

本文关键字:JavaScript 习语 定义 用于      更新时间:2023-09-26

在JavaScript中定义类的首选习惯用法是什么?我可以为复数定义一个构造函数,如下所示:

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;
    }
}

或者我可以这样做:

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;
    }
}

既然《JavaScript: The Good Parts》和《JavaScript The Definitive Guide》这两本教科书都没有定义类,那么我怀疑它们不是等价的——如果我打算使用继承,我怀疑我需要使用prototype。这对我来说有点模糊,有人能解释一下吗?

我知道我可以使用上述文本中建议的Object.create()方法并以原型方式做事,但我很少看到人们在实践中这样做。

在第一个例子中,每个新对象都有自己的add()方法副本。

在第二个示例中,每个新对象共享通过prototypeadd()函数的一个副本。