微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.$= $;  
}());

原文地址:https://www.jb51.cc/jquery/153912.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐