我使用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的Simple JavaScript Inheritance.
var MyWidget = Class.extend({ init: function(widget_name){ this.widget_name = widget_name; }, doSomething: function() { alert('my name is ' + this.widget_name); } });
注意:上面演示的"Class"对象不包含在jQuery本身中 - 它是来自jQuery先生本人的25行片段,在上面的文章中提供.
为什么不使用JavaScript本身提供的简单OOP ...早在jQuery之前?
var myClass = function(){}; myClass.prototype = { some_property: null, some_other_property: 0, doSomething: function(msg) { this.some_property = msg; alert(this.some_property); } };
然后你只需要创建一个类的实例:
var myClassObject = new myClass(); myClassObject.doSomething("Hello Worlds");
简单!
总结到目前为止我学到的东西:
下面是使Class.extend()在jquery中工作的Base函数(由John Resig 从简单JavaScript继承复制):
// 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.