Phi*_*lak 6 javascript jquery class
我正试图从Prototype转移到jQuery,最后一件事我无法弄清楚如何在新库中做.
这是我以前用Prototype做的事情:
MyClass = Class.create();
MyClass.prototype = {
initialize: function(options) {
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以创建一个新MyClass的:
var mc = new MyClass({});
Run Code Online (Sandbox Code Playgroud)
jQuery有没有类似Prototype的东西Class.create()?如果没有,如何在没有图书馆的情况下获得同样的东西?
Dev*_*von 15
我使用jquery 扩展函数来扩展类原型.
例如:
MyWidget = function(name_var) {
this.init(name_var);
}
$.extend(MyWidget.prototype, {
// object variables
widget_name: '',
init: function(widget_name) {
// do initialization here
this.widget_name = widget_name;
},
doSomething: function() {
// an example object method
alert('my name is '+this.widget_name);
}
});
// example of using the class built above
var widget1 = new MyWidget('widget one');
widget1.doSomething();
Run Code Online (Sandbox Code Playgroud)
jQuery使用标准的javascript功能来创建新类.
网上有一些很好的例子,但我建议你看一下David Flanagan的书Javascript:The Definitive Guide.
我道歉,我完全误解了你原来的帖子.我猜你真的想知道如何扩展jQuery $对象.这很容易实现,有很多插件用于这样做.jQuery网站上有一个教程可以做到这一点:jQuery入门
但基本上,你使用
jQuery.fn.foobar = function() {
// do something
};
Run Code Online (Sandbox Code Playgroud)