我正在尝试弄清楚如何正确构建我的 Javascript 类(或单例对象)。
这些(“类”和单例对象)之间存在很大差异。您的前几个示例是一次性对象(单例)。您的第三个(最后一个)示例创建了一个 构造函数,它允许您创建共享同一原型的多个对象。我建议扩充构造函数上的prototype 属性,而不是像你正在做的那样替换它,例如:
var Thingy = function() { // Or use a function declaration rather than expression
// Optional initialization code here
};
Thingy.prototype.foo = 'bar';
Thingy.prototype.method = function() {
// Method code here
};
(按照惯例,构造函数以大写字母开头。)
您使用哪个(单例或构造函数)取决于您的需要。
从 ES2015(又名“ES6”)开始,它更简单,尽管没有用于定义非方法原型属性的新语法(您的 foo);可能会在 ES2017 或 ES2018 中,一旦this proposal 向前移动,但在那之前:
class Thingy {
constructor() {
// Optional initialization code here
}
method() {
// Method code here
}
}
Thingy.prototype.foo = 'bar';
如果您需要进入继承层次结构,在旧的 ES5 语法中会涉及到相当多的管道:
var Base = function() {
};
Base.prototype.method = function(arg1) {
// ...
};
var Derived = function() {
Base.call(this);
};
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;
Derived.prototype.method = function(arg1) {
// Using Base's `method`, if desired, is a bit ugly:
Base.prototype.method.call(this, arg1);
};
...这就是为什么您过去经常看到库介入的原因,例如 Prototype 的 Class 的东西,或者我自己的 Lineage;这些在 ES2015 语法中已经过时了,不过,这让它变得非常容易:
class Base {
method(arg1) {
// ...
}
}
class Derived extends Base {
method(arg1) {
// Use's the superclass's `method`, if desired, is easy:
super.method(arg1);
}
}
关于您问题的标题:
创建 Javascript 类的正确方法是什么?
有几种同样正确的方法可以在 JavaScript 中创建对象的“类”,因为 JavaScript 是一种非常灵活的语言。有标准的构造函数、“builder”函数、Object.create(在支持 ES5 的环境中)可以让您进行更直接的原型继承,以及其他几个。 JavaScript 的一大优点是您可以选择自己的“类”风格。