原创

JavaScript 不采用 prototype和new来实现继承机制的方式

JavaScript中要实现继承,其实就是实现三层含义:

1、子类的实例可以共享父类的方法;

2、子类可以覆盖父类的方法或者扩展新的方法;

3、子类和父类都是子类实例的“类型”。

JavaScript中,并不直接从语法上支持继承,但是可以通过模拟的方法来实现继承,以下是关于实现继承的几种方法的总结:

1、构造继承法

2、原型继承法

3、实例继承法

4、拷贝继承法

具体实现代码如下:

/**
  * Created by www.yoodb.com
  * 不使用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");
 birdJim.fly();
 birdTom.eat("rice");
 birdTom.fly();
~阅读全文-人机检测~

微信公众号“Java精选”(w_z90110),专注Java技术干货分享!让你从此路人变大神!回复关键词领取资料:如Mysql、Hadoop、Dubbo、Spring Boot等,免费领取视频教程、资料文档和项目源码。微信搜索小程序“Java精选面试题”,内涵3000+道Java面试题!

涵盖:互联网那些事、算法与数据结构、SpringMVC、Spring boot、Spring Cloud、ElasticSearch、Linux、Mysql、Oracle等

评论

分享:

支付宝

微信