javascript – jQuery如何使用$object构造函数和与$关联的方法?

那么jQuery可以做$(“#foo”).addClass(“bar”)和$.ajax()?

我正在创建一个微型JavaScript框架,并且想要创建一个对象的新实例,例如$(“#hello”).与此对象有一些相关的方法,如addClass,css等,就像jQuery一样.所以我可以做一些像

$("#foo").addClass("remove").css("color","red");

我已经成功地创造了这个.但是,当我想从这个对象调用一个方法(如$.ajax)时,构造函数被覆盖,我可以调用$.ajax,而不是$(“#foo”).

基本上,jQuery如何做?

解决方法

好的,$函数不仅仅是一个函数,而是一个对象,就像所有函数一样.所以它可以有方法.这就是ajax,这是$函数的一种方法.所以我们可以从这开始:
$= function(obj) {
  // some code 
};
$.ajax = function (arg1,arg2) {
  // some ajax-y code
};

到现在为止还挺好.现在,我们在$函数中放置了什么?那么它必须返回一个对象,该对象必须有一些很好的方法定义在它上面.所以我们需要一个构造函数(给我们新的对象)和一个原型(为这些对象提供漂亮的方法).

$= function(obj) {
  var myConstructor = function (obj) {
    this.wrappedobj = obj;
  };

  myConstructor.prototype = {
    niftyMethod: function () {
      // do something with this.wrappedobj
      return this; // so we can chain method calls
    },anotherNiftyMethod: function (options) {
      // do something with this.wrappedobj and options
      return this; 
    }
  };

  return new myConstructor(obj);
};

所以我们有它.我们做得到:

var mySnazzObject = $("whatever");
mySnazzObject.niftyMethod().anotherNiftyMethod(true);

我们可以这样做:

$.ajax("overthere.html",data);

显然,jQuery比这更多,但它的确是令人印象深刻的,但这是一般的想法.

更新:AS @Raynos足够好观察,没有提供建设性的答案,我的原始代码将创建原型广告无限.所以我们使用匿名自动执行函数来分别声明构造函数和原型:

(function () {
  var myConstructor = function (obj) {
    this.wrappedobj = obj;
  };

  myConstructor.prototype = {
    niftyMethod: function () {
      // do something with this.wrappedobj
      return this; // so we can chain method calls
    },anotherNiftyMethod: function (options) {
      // do something with this.wrappedobj and options
      return this; 
    }
  };

  var $= function(obj) {
    return new myConstructor(obj);        
  };

  $.ajax = function (arg1,arg2) {
    // some ajax-y code
  };

  window.$= $;  
}());

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...