program tip

jQuery로 객체 지향 클래스를 만드는 더 좋은 방법이 있습니까?

radiobox 2020. 11. 2. 07:48
반응형

jQuery로 객체 지향 클래스를 만드는 더 좋은 방법이 있습니까?


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

이 작업을 수행하는 더 좋은 방법이 있습니까? 두 개 대신 하나의 문으로 위의 클래스를 만드는 더 깨끗한 방법이 있습니까?


저는 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);
  }
});

NB : 위에서 설명한 "Class"객체는 jQuery 자체에 포함되어 있지 않습니다. 위의 기사에서 제공 한 jQuery 씨의 25 줄 스 니펫입니다.


자바 스크립트 자체가 제공하는 단순한 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");

단순한!


지금까지 배운 내용을 요약하면 다음과 같습니다.

Here is the Base function that makes Class.extend() work in jQuery (Copied from Simple JavaScript Inheritance by John Resig):

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

Once you have run executed this code, then that makes the following code from insin's answer possible:

var MyWidget = Class.extend({
  init: function(widget_name){
    this.widget_name = widget_name;
  },

  doSomething: function() {
    alert('my name is ' + this.widget_name);
  }
});

This is a nice, clean solution. But I'm interested to see if anyone has a solution that doesn't require adding anything to jquery.


jQuery doesn't offer that. But Prototype does, via Class.create.


I found this website a impressive one for oops in javascript Here


This is long gone dead, but if anyone else searches for jQuery creating class - check this plugin: http://plugins.jquery.com/project/HJS

참고URL : https://stackoverflow.com/questions/84716/is-there-a-better-way-to-create-an-object-oriented-class-with-jquery

반응형