欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

學(xué)習(xí)JavaScript設(shè)計(jì)模式(鏈?zhǔn)秸{(diào)用)

 更新時(shí)間:2015年11月26日 14:49:19   作者:小平果118  
這篇文章主要帶領(lǐng)大家學(xué)習(xí)JavaScript設(shè)計(jì)模式,其中重點(diǎn)介紹鏈?zhǔn)秸{(diào)用,感興趣的小伙伴們可以參考一下

1、什么是鏈?zhǔn)秸{(diào)用
這個(gè)很容易理解,例如:

$(this).setStyle('color', 'red').show();

一般的函數(shù)調(diào)用和鏈?zhǔn)秸{(diào)用的區(qū)別:調(diào)用完方法后,return this返回當(dāng)前調(diào)用方法的對(duì)象。

function Dog(){
    this.run= function(){
      alert("The dog is running....");
      return this;//返回當(dāng)前對(duì)象 Dog
    };
    this.eat= function(){
      alert("After running the dog is eatting....");
      return this;//返回當(dāng)前對(duì)象 Dog

    };
    this.sleep= function(){
      alert("After eatting the dog is running....");
      return this;//返回當(dāng)前對(duì)象 Dog

    };
  }
  //一般的調(diào)用方式;
/* var dog1 =new Dog();
  dog1.run();
  dog1.eat();
  dog1.sleep();*/
  var dog2 = new Dog();
  dog2.run().eat().sleep();

2、分解鏈?zhǔn)秸{(diào)用

鏈?zhǔn)秸{(diào)用其實(shí)是兩個(gè)部分:

1).操作對(duì)象(也就是被操作的DOM元素,如上例的$(this))

2).操作方法(具體要做什么事情,如上例的setStyle和show)

如何實(shí)現(xiàn)操作對(duì)象與操作方法

創(chuàng)建一般的$函數(shù):

function $(){
  var elements = [];
  for(var i= 0,len=arguments.length; i<len; i++){
    var element = arguments[i];
    if(typeof element==='string'){
      element = document.getElementById(element);
    }
    if(arguments.length==1){
      return element;
    }
    elements.push(element);
  }
  return elements;
}

但是,如果把這個(gè)函數(shù)改造為一個(gè)構(gòu)造器,把那些元素作為數(shù)組保存在一個(gè)實(shí)例屬性中,并讓所有定義在構(gòu)造器函數(shù)的prototype屬性所指對(duì)象中的方法都返回用以調(diào)用方法的那個(gè)實(shí)例的引用,那么它就具有了鏈?zhǔn)秸{(diào)用的能力。(說了這么多,就是在每個(gè)方法最后return this;),

我首先需要把這個(gè)$函數(shù)改為一個(gè)工廠方法,它負(fù)責(zé)創(chuàng)建支持鏈?zhǔn)秸{(diào)用的對(duì)象。這個(gè)函數(shù)應(yīng)該能接受元素?cái)?shù)組形式的參數(shù),以便我們能夠使用與原來一樣的公用接口。這樣以來,它就具有了進(jìn)行鏈?zhǔn)秸{(diào)用的能力。

改造后如下:

(function(){
  function _$(els){
    this.elements = [];//把那些元素作為數(shù)組保存在一個(gè)實(shí)例屬性中,
    for(var i= 0, len=els.length; i<len; i++){
      var element = els[i];
      if(typeof element==='string'){
        element = document.getElementById(element);
      }
      this.elements.push(element);
    }
  }

  _$.prototype = {
    each: function(fn){
      for(var i= 0,len=this.elements.length; i<len; i++){
        fn.call(this, this.elements[i]);
      }
      return this; //在每個(gè)方法的最后return this;
    },
    setStyle: function(prop, val){
      this.each(function(el){
        el.style[prop] = val;
      });
      return this; //在每個(gè)方法的最后return this;
    },
    show: function(){
      var that = this;
      this.each(function(el){
        that.setStyle('display', 'block');
      });
      return this; //在每個(gè)方法的最后return this;
    },
    addEvent: function(type, fn){
      var add = function(el){
        if(window.addEventListener){
          el.addEventListener(type, fn, false);
        }else if(window.attachEvent){
          el.addEvent('on'+type, fn);
        }
      };
      this.each(function(el){
        add(el);
      });
      return this; //在每個(gè)方法的最后return this;
    }
  }
  window.$ = function(){
    return new _$(arguments);
  }
})();

在最后return this,這就將調(diào)用方法的對(duì)象傳給調(diào)用鏈上的下一個(gè)方法。

3、模擬jquery底層鏈?zhǔn)骄幊?/strong>

// 塊級(jí)作用域
//特點(diǎn)1 程序啟動(dòng)的時(shí)候 里面的代碼直接執(zhí)行了
//特點(diǎn)2 內(nèi)部的成員變量 外部無法去訪問 (除了不加var修飾的變量)

(function(window , undefined){
  // $ 最常用的對(duì)象 返回給外界 大型程序開發(fā) 一般使用'_'作為私用的對(duì)象(規(guī)范)
  function _$(arguments){
    //實(shí)現(xiàn)代碼...這里僅實(shí)現(xiàn)ID選擇器
    // 正則表達(dá)式匹配id選擇器
    var idselector = /#\w+/ ;
    this.dom ;   // 此屬性 接受所得到的元素
    // 如果匹配成功 則接受dom元素  arguments[0] = '#inp'
    if(idselector.test(arguments[0])){
      this.dom = document.getElementById(arguments[0].substring(1));
    } else {
      throw new Error(' arguments is error !');
    }
  };

  // 在Function類上擴(kuò)展一個(gè)可以實(shí)現(xiàn)鏈?zhǔn)骄幊痰姆椒?
  Function.prototype.method = function(methodName , fn){
    this.prototype[methodName] = fn ;
    return this ; //鏈?zhǔn)骄幊痰年P(guān)鍵
  }

  // 在_$的原型對(duì)象上 加一些公共的方法
  _$.prototype = {
    constructor : _$ ,
    addEvent:function(type,fn){
      // 給你的得到的元素 注冊(cè)事件
      if(window.addEventListener){// FF 
        this.dom.addEventListener(type , fn);
      } else if (window.attachEvent){// IE
        this.dom.attachEvent('on'+type , fn);
      }
      return this ; 
    },
    setStyle:function(prop , val){
      this.dom.style[prop] = val ;
      return this ;
    }
  };


   // window 上先注冊(cè)一個(gè)全局變量 與外界產(chǎn)生關(guān)系
  window.$ = _$ ;
  // 寫一個(gè)準(zhǔn)備的方法
  _$.onReady = function(fn){ 
    // 1 實(shí)例化出來_$對(duì)象 真正的注冊(cè)到window上
    window.$ = function(){
      return new _$(arguments);
    };
    // 2 執(zhí)行傳入進(jìn)來的代碼
    fn();
    // 3 實(shí)現(xiàn)鏈?zhǔn)骄幊?
    _$.method('addEvent',function(){
      // nothing to do
    }).method('setStyle',function(){
      // nothing to do
    });

  };

})(window); // 程序的入口 window傳入作用域中


$.onReady(function(){
  var inp = $('#inp');
  //alert(inp.dom.nodeName);
  //alert($('#inp'));
  inp.addEvent('click',function(){
    alert('我被點(diǎn)擊了!');
  }).setStyle('backgroundColor' , 'red');
});

4、使用回調(diào)函數(shù)從支持鏈?zhǔn)秸{(diào)用的方法獲取數(shù)據(jù)

鏈?zhǔn)秸{(diào)用很適合于賦值器方法,但對(duì)于取值器方法,就不方便了,因?yàn)槊總€(gè)方法返回的都是this啊。

不過,變通的方法還是有的,那就是回調(diào)函數(shù)。

未使用回調(diào)函數(shù)時(shí)

//without callback
window.API = window.API || function(){
  var name = 'JChen';
  this.setName = function(newName){
    name = newName;
    return this;
  };
  this.getName = function(){
    return name;
  };
};
var o = new API();
console.log(o.getName());
console.log(o.setName('Haha').getName());

使用回調(diào)函數(shù)時(shí)

//with callback
window.API2 = window.API2 || function(){
  var name = 'JChen';
  this.setName = function(newName){
    name = newName;
    return this;
  };
  this.getName = function(callback){
    callback.call(this, name);
    return this;
  };
};
var o2 = new API2();
o2.getName(console.log).setName('Hehe').getName(console.log);

在使用回調(diào)函數(shù)時(shí)候callback.call(this, name)在一般情況下是沒問題的,但是,這個(gè)例子偏偏用到了console.log,那么就有問題了。原因是console的this是指向console而不是winodw。

這個(gè)問題也很好解決。如下:

//with callback
window.API2 = window.API2 || function(){
  var name = 'JChen';
  this.setName = function(newName){
    name = newName;
    return this;
  };
  this.getName = function(callback){
    callback.call(this, name);
    return this;
  };
};
var o2 = new API2();
var log = function(para){
  console.log(para);
};
o2.getName(log).setName('Hehe').getName(log);

鏈?zhǔn)秸{(diào)用這種風(fēng)格有助于簡(jiǎn)化代碼的編寫工作,讓代碼更加簡(jiǎn)潔、易讀,同時(shí)也避免多次重復(fù)使用一個(gè)對(duì)象變量,希望大家可以熟練掌握。

相關(guān)文章

最新評(píng)論