【发布时间】:2012-08-16 11:01:05
【问题描述】:
我正在寻找在 JavaScript 中定义类的方法。我想出了混合模块和原型模式,但不确定我是否错过了什么。基本上我想使用'this'关键字。示例:
var A = function()
{
this.x = 10;
};
A.prototype = (function()
{
function privatePrint()
{
alert("Printing from private! x:" + this.x);
}
this.print = function()
{
privatePrint.call(this);
};
return this;
}).apply(A.prototype);
var a = new A();
a.print();
返回值只是为了可读性 - A.prototype 可以在开头使用。
我也尝试过的模式:
- 模块:不能使用“新”关键字。
- 原型,展示原型: 如果在原型声明中声明了私有函数,则没有扩展 (对象返回的公共方法)
我的方法可以接受吗?
【问题讨论】:
-
我看不出这种方法有什么用...有什么好处?这似乎令人困惑。为什么不只是
A.prototype = { ... }.. -
设置prototype到和object后,不能用同样的操作来扩展它。
标签: javascript design-patterns module this prototype