有没有更好的方法用jquery创建面向对象的类?
时间:2020-03-05 18:59:12 来源:igfitidea点击:
我使用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();
有一个更好的方法吗?有没有一种更清洁的方法可以仅使用一个语句而不是两个语句来创建上述类?
解决方案
回答
我非常喜欢John Resig的"简单JavaScript继承"。
var MyWidget = Class.extend({ init: function(widget_name){ this.widget_name = widget_name; }, doSomething: function() { alert('my name is ' + this.widget_name); } });
注意:上面演示的"类"对象未包含在jQuery本身中,这是上面文章中的jQuery先生本人的25行代码片段。
回答
jQuery不提供该功能。但是原型是通过Class.create实现的。
回答
总结到目前为止我学到的东西:
这是使Class.extend()在jquery中工作的基本函数(由John Resig从Simple JavaScript Inherited复制):
// Inspired by base2 and Prototype (function(){ var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/; // The base Class implementation (does nothing) this.Class = function(){}; // Create a new Class that inherits from this class Class.extend = function(prop) { var _super = this.prototype; // Instantiate a base class (but only create the instance, // don't run the init constructor) initializing = true; var prototype = new this(); initializing = false; // Copy the properties over onto the new prototype for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name]) ? (function(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; })(name, prop[name]) : prop[name]; } // The dummy class constructor function Class() { // All construction is actually done in the init method if ( !initializing && this.init ) this.init.apply(this, arguments); } // Populate our constructed prototype object Class.prototype = prototype; // Enforce the constructor to be what we expect Class.constructor = Class; // And make this class extendable Class.extend = arguments.callee; return Class; }; })();
一旦运行了该代码,就可以从insin的答案中获得以下代码:
var MyWidget = Class.extend({ init: function(widget_name){ this.widget_name = widget_name; }, doSomething: function() { alert('my name is ' + this.widget_name); } });
这是一个不错的,干净的解决方案。但是我很想看看是否有人有不需要向jquery添加任何内容的解决方案。
回答
这早已荡然无存,但是如果其他人搜索创建类的jQuery,请检查此插件:
http://plugins.jquery.com/project/HJS