你的代码可以运行,但效率不够高,因为它会给每个实例都赋予一个 getInfo
函数。这是可以避免的。你可以使用以下模式来模拟JS中的类。
基础模式
要模拟类属性/方法,请在构造函数上设置属性/方法。
function Apple() {};
Apple.classProperty = some_value;
Apple.classMethod = some_method;
为了模拟实例属性,你可以在构造函数内设置(就像你在代码中所做的):
function Apple() {
this.property = some_instance_value;
};
为了模拟一个实例方法,你可以在构造函数的`Constructor.prototype`中设置函数,这些函数将在其所有实例之间共享。
function Apple() {};
Apple.prototype.instanceMethod = function () {...};
高级模式
如果您想设置私有/特权方法,Crockford提供了非常有用的模式。
私有方法-仅对构造函数可用:
function Constructor(...) {
var that = this;
var membername = value;
function membername(...) {...}
}
特权方法 - 可以访问私有方法并对公众可用:
function Constructor(...) {
this.membername = function (...) {...};
}