我想将原型javascript框架用于其“类”和继承功能。对于其他一切,我将使用jQuery。是否有一个极简主义版本的原型会给我这个功能?如果我不使用它,我不希望整个库的额外开销。
具体来说,我想要允许我按如下方式定义类的类和继承功能(来自维基百科的例子):
var FirstClass = Class.create( {
// The initialize method serves as a constructor
initialize: function () {
this.data = "Hello World";
}
});
并扩展另一个类:
MyNewClass = Class.create( FirstClass, {
//Override the initialize method
initialize: function() {
//..
},
// ...more methods add ...
});
另外我不希望框架之间发生冲突(即$
仅应该由jQuery使用..我只想要类的原型(或任何其他建议没问题)创造/继承)。
答案 0 :(得分:5)
Inheritance.js是开发Prototype库的人受到启发的模型,我认为这就是你所要求的。
注意:$super
似乎是this.parent
,如下面的评论中所述。
答案 1 :(得分:3)
如果您正在寻找简约的东西:
function clone(obj) {
if(typeof obj !== 'undefined') {
clone.prototype = obj;
return new clone;
}
}
function copy(dest, src) {
for(var name in src) {
if(src.hasOwnProperty(name))
dest[name] = src[name];
}
}
function classof(constructor) {
return {
extend : function(base) {
constructor.prototype = clone(base.prototype);
return this;
},
mixin : function(members) {
copy(constructor.prototype, members);
return this;
}
};
}
使用示例:
// base class:
function Foo(value) {
this.value = value;
}
classof(Foo).mixin({
inc : function() { ++this.value; }
});
// derived class:
function Bar() {
Foo.apply(this, arguments);
}
classof(Bar).extend(Foo).mixin({
dec : function() { --this.value; }
});
var bar = new Bar(42);
bar.inc();
bar.dec();
答案 2 :(得分:2)
不要混合Prototype和jQuery。我的经验表明他们不能很好地在一起。由于优质的语法糖,我个人的偏好是使用Prototype。
没有办法禁用Prototype的$ -function。你可以通过jQuery.noConflict()禁用jQuery对$的使用 - 但它并不完美。
正如@mhtiza所说,如果您决定坚持使用jQuery,请使用Interitance.js作为类糖。
答案 3 :(得分:1)
对于1.7.1版本,我删除了prototype.js文件中第1625行以下的所有内容,并且我不再与bootstrap和jquery发生冲突。 Class.create函数仍然有效。 class.create也是我唯一想要的方法。