【问题标题】:Is there a better way to create an object-oriented class with jQuery?有没有更好的方法来使用 jQuery 创建一个面向对象的类?
【发布时间】:2010-09-10 05:27:39
【问题描述】:

我使用 jQuery extend 函数来扩展类原型。

例如:

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();

有没有更好的方法来做到这一点?有没有一种更简洁的方法可以只用一个语句而不是两个语句来创建上面的类?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    我很喜欢 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 行 sn-p,在上面的文章中提供。

    【讨论】:

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

    为什么不直接使用 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");
    

    简单!

    【讨论】:

    • 库独立,很不错!虽然我更喜欢声明更“类”,例如:function MyClassName() {};
    • @CrazyMerlin 你不应该在构造函数中定义像 some_property 和 some_other_property 这样的属性并在原型上定义方法。这样每个实例都可以获得自己的属性,而不是相互共享它。跨度>
    • 当然,如果您使用的是 ES6 语法。这只是一个遗留示例,表明几代前的 vanilla JS 具有此功能,而无需使用任何类型的库。 ES6 太棒了!
    【解决方案3】:

    总结一下我目前学到的东西:

    这是使 Class.extend() 在 jQuery 中工作的基本函数(由 John Resig 从Simple JavaScript Inheritance 复制):

    // 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's answer的以下代码就成为可能:

    var MyWidget = Class.extend({
      init: function(widget_name){
        this.widget_name = widget_name;
      },
    
      doSomething: function() {
        alert('my name is ' + this.widget_name);
      }
    });
    

    这是一个不错的、干净的解决方案。但我很想看看是否有人有不需要向 jquery 添加任何内容的解决方案。

    【讨论】:

      【解决方案4】:

      jQuery 不提供。但是Prototype 确实如此,通过Class.create

      【讨论】:

        【解决方案5】:

        我发现这个网站是一个令人印象深刻的 oops in javascript Here

        【讨论】:

          【解决方案6】:

          这早就死了,但如果其他人搜索 jQuery 创建类 - 检查这个插件: http://plugins.jquery.com/project/HJS

          【讨论】:

          • 如果你已经发现用链接回答是有问题的,因为内容经常消失,为什么会重复同样的错误呢?如果您在此处包含相关有用的关键点,则不是抄袭。 (此消息主要针对到达这里并寻求答案的人。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-07-17
          • 2013-11-09
          • 2010-11-23
          • 1970-01-01
          • 2018-04-20
          • 2018-02-15
          • 2014-07-06
          相关资源
          最近更新 更多