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

JavaScript不使用prototype和new實(shí)現(xiàn)繼承機(jī)制

 更新時(shí)間:2014年12月29日 11:07:58   投稿:hebedich  
這篇文章主要介紹了JavaScript不使用prototype和new實(shí)現(xiàn)繼承機(jī)制的相關(guān)資料,需要的朋友可以參考下

此方法并非筆者原創(chuàng),筆者只是在前輩的基礎(chǔ)上,加以總結(jié),得出一種簡潔實(shí)用的JavaScript繼承方法。

      傳統(tǒng)的JavaScript繼承基于prototype原型鏈,并且需要使用大量的new操作,代碼不夠簡潔,可讀性也不是很強(qiáng),貌似還容易受到原型鏈污染。

      筆者總結(jié)的繼承方式,簡潔明了,雖然不是最好的方式,但希望能給讀者帶來啟發(fā)。

      好了,廢話不多說,直接看代碼,注釋詳盡,一看就懂~~~

復(fù)制代碼 代碼如下:

 /**
  * Created by 楊元 on 14-11-11.
  * 不使用prototype實(shí)現(xiàn)繼承
  *
  */
 /**
  * Javascript對象復(fù)制,僅復(fù)制一層,且僅復(fù)制function屬性,不通用!
  * @param obj  要復(fù)制的對象
  * @returns  Object
  */
 Object.prototype.clone = function(){
     var _s = this,
         newObj = {};
     _s.each(function(key, value){
         if(Object.prototype.toString.call(value) === "[object Function]"){
             newObj[key] = value;
         }
     });
     return newObj;
 };
 /**
  * 遍歷obj所有自身屬性
  *
  * @param callback 回調(diào)函數(shù)?;卣{(diào)時(shí)會(huì)包含兩個(gè)參數(shù): key 屬性名,value 屬性值
  */
 Object.prototype.each = function(callback){
     var key = "",
         _this = this;
     for (key in _this){
         if(Object.prototype.hasOwnProperty.call(_this, key)){
             callback(key, _this[key]);
         }
     }
 };
 /**
  * 創(chuàng)建子類
  * @param ext obj,包含需要重寫或擴(kuò)展的方法。
  * @returns Object
  */
 Object.prototype.extend = function(ext){
     var child = this.clone();
     ext.each(function(key, value){
         child[key] = value;
     });
     return child;
 };
 /**
  * 創(chuàng)建對象(實(shí)例)
  * @param arguments 可接受任意數(shù)量參數(shù),作為構(gòu)造器參數(shù)列表
  * @returns Object
  */
 Object.prototype.create = function(){
     var obj = this.clone();
     if(obj.construct){
         obj.construct.apply(obj, arguments);
     }
     return obj;
 };
 /**
  * Useage Example
  * 使用此種方式繼承,避免了繁瑣的prototype和new。
  * 但是目前筆者寫的這段示例,只能繼承父類的function(可以理解為成員方法)。
  * 如果想繼承更豐富的內(nèi)容,請完善clone方法。
  *
  *
  */
 /**
  * 動(dòng)物(父類)
  * @type {{construct: construct, eat: eat}}
  */
 var Animal = {
     construct: function(name){
         this.name = name;
     },
     eat: function(){
         console.log("My name is "+this.name+". I can eat!");
     }
 };
 /**
  * 鳥(子類)
  * 鳥類重寫了父類eat方法,并擴(kuò)展出fly方法
  * @type {子類|void}
  */
 var Bird = Animal.extend({
     eat: function(food){
         console.log("My name is "+this.name+". I can eat "+food+"!");
     },
     fly: function(){
         console.log("I can fly!");
     }
 });
 /**
  * 創(chuàng)建鳥類實(shí)例
  * @type {Jim}
  */
 var birdJim = Bird.create("Jim"),
     birdTom = Bird.create("Tom");
 birdJim.eat("worm");  //My name is Jim. I can eat worm!
 birdJim.fly();  //I can fly!
 birdTom.eat("rice");  //My name is Tom. I can eat rice!
 birdTom.fly();  //I can fly!

相關(guān)文章

最新評論