我们创建了一组依赖于 Prototype 的类实现(以及一些 Object.extend)的类。
问题是原型(prototype)在与我们的其他应用程序集成时会产生麻烦(即使使用“无冲突”适配器等)。
有人知道一个不会扰乱全局范围的兼容类实现吗?或者有人能够“提取”原型(prototype)来单独使用它吗?
最佳答案
我wrote one几年前(我应该重新访问它,并给它一个合适的名称),因为我不喜欢 Prototype 对“父类(super class)”调用方法的处理,这涉及每次创建一个函数调用重写的方法(是的,确实如此)。除了如何进行 super 调用之外,它与 Prototype 非常相似;您可以轻松地将其放入并搜索 super
在你的代码中并更改它。我的实现也使得使用起来更容易 named functions rather than anonymous ones ,这很有用,原因有很多,尤其是因为它可以帮助您的工具为您提供帮助。它还使私有(private)“类”方法变得微不足道。详细信息如下。
但你不必使用我的。还有其他选项需要稍微多一些工作来将代码迁移到其中,但可能不会更多:
- 约翰·雷西格的 simple inheritance
- 迪恩·爱德华兹的mechanism
我对它们的问题是它们都使用函数反编译(Prototype 的 Class
也是如此),而函数反编译(例如,在函数上调用 toString
)从未标准化,并且在某些移动设备上不起作用浏览器。如果函数反编译不起作用,Resig 的机制将继续工作,但在这种情况下它会增加每个方法的开销(而不仅仅是进行 super 调用的方法)。我的机制根本不使用函数反编译,不会为方法调用增加任何开销,甚至使 super 调用变得高效。
如果您使用我的机制并且您的原型(prototype)代码如下所示:
var SuperThingy = Class.create({
foo: function(arg) {
console.log("SuperThingy: " + arg);
this._pseudoPrivate();
},
_pseudoPrivate: function() {
console.log("I'm not really private.");
}
});
var Thingy = Class.create(SuperThingy, {
foo: function(super, arg) {
console.log("Thingy: " + arg);
super(arg);
}
});
您可以进行最小的更改:
var SuperThingy = Helper.makeClass({
foo: function(arg) {
console.log("SuperThingy: " + arg);
this._pseudoPrivate();
},
_pseudoPrivate: function() {
console.log("I'm not really private.");
}
});
var Thingy = Helper.makeClass(SuperThingy, {
foo: function(arg) {
console.log("Thingy: " + arg);
this.callSuper(arguments, arg);
}
});
...或者您可以进行稍大的更改并获得速度提升的好处( callSuper
使用 arguments.callee
,这是慢),正确命名的函数(用于调试和这样),以及真正的私有(private)函数:
var SuperThingy = Helper.makeClass(function() {
function SuperThingy_foo(arg) {
console.log("SuperThingy: " + arg);
trulyPrivate.call(this);
}
function trulyPrivate() {
console.log("I'm truly private.");
}
return {foo: SuperThingy_foo};
});
var Thingy = Helper.makeClass(SuperThingy, function() {
function Thingy_foo(arg) {
console.log("Thingy: " + arg);
foo.$super.call(this, arg);
}
return {foo: Thingy_foo};
});
关于javascript - Prototype.js 类系统的替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7594473/