源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JavaScript不使用prototype和new实现继承机制

  • 时间:2022-01-09 23:39 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JavaScript不使用prototype和new实现继承机制
此方法并非笔者原创,笔者只是在前辈的基础上,加以总结,得出一种简洁实用的JavaScript继承方法。       传统的JavaScript继承基于prototype原型链,并且需要使用大量的new操作,代码不够简洁,可读性也不是很强,貌似还容易受到原型链污染。       笔者总结的继承方式,简洁明了,虽然不是最好的方式,但希望能给读者带来启发。       好了,废话不多说,直接看代码,注释详尽,一看就懂~~~
[u]复制代码[/u] 代码如下:
 /**   * Created by 杨元 on 14-11-11.   * 不使用prototype实现继承   *   */  /**   * Javascript对象复制,仅复制一层,且仅复制function属性,不通用!   * @param obj  要复制的对象   * @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 回调函数。回调时会包含两个参数: 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]);          }      }  };  /**   * 创建子类   * @param ext obj,包含需要重写或扩展的方法。   * @returns Object   */  Object.prototype.extend = function(ext){      var child = this.clone();      ext.each(function(key, value){          child[key] = value;      });      return child;  };  /**   * 创建对象(实例)   * @param arguments 可接受任意数量参数,作为构造器参数列表   * @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(可以理解为成员方法)。   * 如果想继承更丰富的内容,请完善clone方法。   *   *   */  /**   * 动物(父类)   * @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方法,并扩展出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!");      }  });  /**   * 创建鸟类实例   * @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!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部