有没有更好的方法来创建一个使用jquery的面向对象的类? [英] Is there a better way to create an object-oriented class with jquery?

查看:107
本文介绍了有没有更好的方法来创建一个使用jquery的面向对象的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use the jquery extend function to extend a class prototype.

例如:

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

有更好的方法吗?是否有更简洁的方法来创建上面的类只有一个语句而不是两个?

Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two?

推荐答案

我非常喜欢John Resig的简单的JavaScript继承

I quite like John Resig's 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本身中 - 它是25行jQuery先生自己的片段,在上面的文章中提供。

NB: The "Class" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above.

这篇关于有没有更好的方法来创建一个使用jquery的面向对象的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆