有没有更好的方法用jQuery创建面向对象的类?


71

我使用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();

有一个更好的方法吗?有没有一种更清洁的方法来创建上面的类而仅用一个语句而不是两个语句?

Answers:


53

我非常喜欢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);
  }
});

注意:上面演示的“类”对象不包含在jQuery本身中-这是上面文章中jQuery先生本人的25行代码片段。


5
啊 我想我应该先阅读整篇文章。这是一个干净的解决方案,尽管它确实需要一些额外的设置代码。
德文郡

24

为什么不仅仅使用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”:function MyClassName() {};
plesatejvlk

9
@CrazyMerlin你不应该这样定义构造函数some_property和some_other_property性质和定义的原型方法..这样每个实例得到它自己的财产,而不是共享其相互之间..
大卫追逐

当然,如果您使用的是ES6语法。这只是一个传统示例,显示了几代前的香草JS具有此功能,而没有使用任何类型的库。ES6很棒!
CrazyMerlin '19

17

总结到目前为止我学到的东西:

这是使Class.extend()在jQuery中工作的基本函数(由John Resig从Simple 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添加任何内容的解决方案。



0

我在javascript发现这个网站一个令人印象深刻的一个哎呀这里


0

这早已荡然无存,但如果有人搜索jQuery创建类,请检查此插件:http : //plugins.jquery.com/project/HJS


如果您已经发现用链接回答是有问题的,因为内容经常消失,那么为什么还要重复同样的错误?如果在此处包括相关的有用要点,这不是窃。(此消息主要针对到达这里并寻求答案的人们)。
Tammi
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.