javascript函数来模拟类,最佳实践?

Joh*_*han 8 javascript class function

我注意到我可以编写类似下面的函数来模拟类.我想知道这是否是最新的方式.任何评论赞赏.谢谢

function Apple(type) {
    this.type = type;
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}

var apple = new Apple('testapple');
apple.color = 'blue';
console.log(apple.getInfo());
Run Code Online (Sandbox Code Playgroud)

ste*_*ang 9

您的代码工作正常但效率不高,因为它为每个实例提供了一个getInfo函数.这可以避免.您可以使用以下模式来模拟JS中的类.

基本模式

要模拟类属性/方法,请在构造函数上设置属性/方法.

function Apple() {};
Apple.classProperty = some_value;
Apple.classMethod = some_method;
Run Code Online (Sandbox Code Playgroud)

要模拟实例属性,可以在构造函数内部进行设置(就像在代码中一样):

function Apple() {
  this.property = some_instance_value;
};
Run Code Online (Sandbox Code Playgroud)

要模拟实例方法,可以在Constructor.prototype其所有实例中共享将要共享的函数

function Apple() {};
Apple.prototype.instanceMethod = function () {...};
Run Code Online (Sandbox Code Playgroud)

高级模式

如果你想设置私有/特权方法,Crockford有非常有用的模式.

私有方法 - 仅对构造函数可用:

function Constructor(...) {
var that = this;
var membername = value;
function membername(...) {...}

}
Run Code Online (Sandbox Code Playgroud)

特权方法 - 可以访问私有方法,并且可以访问公众:

function Constructor(...) {
this.membername = function (...) {...};
}
Run Code Online (Sandbox Code Playgroud)