javascript中的3种继承实现方法


Posted in Javascript onJanuary 27, 2016

使用Object.create实现类式继承

下面是官网的一个例子

//Shape - superclass
function Shape() {
 this.x = 0;
 this.y = 0;
}

Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info("Shape moved.");
};

// Rectangle - subclass
function Rectangle() {
 Shape.call(this); //call super constructor.
}

Rectangle.prototype = Object.create(Shape.prototype);

var rect = new Rectangle();

rect instanceof Rectangle //true.
rect instanceof Shape //true.

rect.move(1, 1); //Outputs, "Shape moved."

此时Rectangle原型的constructor指向父类,如需要使用自身的构造,手动指定即可,如下

Rectangle.prototype.constructor = Rectangle;

使用utilities工具包自带的util.inherites

语法

util.inherits(constructor, superConstructor)
例子

const util = require('util');
const EventEmitter = require('events');

function MyStream() {
  EventEmitter.call(this);
}

util.inherits(MyStream, EventEmitter);

MyStream.prototype.write = function(data) {
  this.emit('data', data);
}

var stream = new MyStream();

console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true

stream.on('data', (data) => {
 console.log(`Received data: "${data}"`);
})
stream.write('It works!'); // Received data: "It works!"

也很简单的例子,其实源码用了ES6的新特性,我们瞅一瞅

exports.inherits = function(ctor, superCtor) {

 if (ctor === undefined || ctor === null)
  throw new TypeError('The constructor to "inherits" must not be ' +
            'null or undefined');

 if (superCtor === undefined || superCtor === null)
  throw new TypeError('The super constructor to "inherits" must not ' +
            'be null or undefined');

 if (superCtor.prototype === undefined)
  throw new TypeError('The super constructor to "inherits" must ' +
            'have a prototype');

 ctor.super_ = superCtor;
 Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};

其中Object.setPrototypeOf即为ES6新特性,将一个指定的对象的原型设置为另一个对象或者null

语法

Object.setPrototypeOf(obj, prototype)
obj为将要被设置原型的一个对象
prototype为obj新的原型(可以是一个对象或者null).

如果设置成null,即为如下示例

Object.setPrototypeOf({}, null);
感觉setPrototypeOf真是人如其名啊,专门搞prototype来玩。
那么这个玩意又是如何实现的呢?此时需要借助宗师__proto__

Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
 obj.__proto__ = proto;
 return obj; 
}

即把proto赋给obj.__proto__就好了。

使用extends关键字

熟悉java的同学应该非常熟悉这个关键字,java中的继承都是靠它实现的。
ES6新加入的class关键字是语法糖,本质还是函数.

在下面的例子,定义了一个名为Polygon的类,然后定义了一个继承于Polygon的类 Square。注意到在构造器使用的 super(),supper()只能在构造器中使用,super函数一定要在this可以使用之前调用。

class Polygon {
 constructor(height, width) {
  this.name = 'Polygon';
  this.height = height;
  this.width = width;
 }
}

class Square extends Polygon {
 constructor(length) {
  super(length, length);
  this.name = 'Square';
 }
}

使用关键字后就不用婆婆妈妈各种设置原型了,关键字已经封装好了,很快捷方便。

Javascript 相关文章推荐
验证控件与Button的OnClientClick事件详细解析
Dec 04 Javascript
JavaScript创建闭包的两种方式的优劣与区别分析
Jun 22 Javascript
关于JS中prototype的理解
Sep 07 Javascript
原生js实现图片层叠轮播切换效果
Feb 02 Javascript
jQuery实现的选择商品飞入文本框动画效果完整实例
Aug 10 Javascript
vue.js国际化 vue-i18n插件的使用详解
Jul 07 Javascript
vue源码入口文件分析(推荐)
Jan 30 Javascript
基于vue打包后字体和图片资源失效问题的解决方法
Mar 06 Javascript
JavaScript中的E-mail 地址格式验证
Mar 28 Javascript
在layui中select更改后生效的方法
Sep 05 Javascript
JQuery插件tablesorter表格排序实现过程解析
May 28 jQuery
微信小程序实现文件预览
Oct 22 Javascript
jQuery+css实现的换页标签栏效果
Jan 27 #Javascript
js实现的彩色方块飞舞奇幻效果
Jan 27 #Javascript
JavaScript下的时间格式处理函数Date.prototype.format
Jan 27 #Javascript
基于JavaScript实现瀑布流效果(循环渐近)
Jan 27 #Javascript
jQuery Easyui学习之datagrid 动态添加、移除editor
Jan 27 #Javascript
js实现简单排列组合的方法
Jan 27 #Javascript
jQuery插件开发精品教程让你的jQuery提升一个台阶
Jan 27 #Javascript
You might like
PHP 日常开发小技巧
2009/09/23 PHP
php 判断访客是否为搜索引擎蜘蛛的函数代码
2011/07/29 PHP
浅析PHP页面局部刷新功能的实现小结
2013/06/21 PHP
php设计模式之委托模式
2016/02/13 PHP
PHP+MySQL实现的简单投票系统实例
2016/02/24 PHP
PHP性能测试工具xhprof安装与使用方法详解
2018/04/29 PHP
PHP sdk实现在线打包代码示例
2020/12/09 PHP
JS 自动安装exe程序
2008/11/30 Javascript
jQuery实现的类flash菜单效果代码
2010/05/17 Javascript
jQuery数组处理方法汇总
2011/06/20 Javascript
jQuery基本选择器选择元素使用介绍
2013/04/18 Javascript
node.js中的fs.readSync方法使用说明
2014/12/17 Javascript
使用Browserify配合jQuery进行编程的超级指南
2015/07/28 Javascript
js实现获取div坐标的方法
2015/11/16 Javascript
第二篇Bootstrap起步
2016/06/21 Javascript
js实现适配不同的屏幕大小
2017/04/10 Javascript
Vue如何引入远程JS文件
2017/04/20 Javascript
JS获取当前地理位置的方法
2017/10/25 Javascript
JS对象与json字符串相互转换实现方法示例
2018/06/14 Javascript
微信小程序全局变量改变监听的实现方法
2019/07/15 Javascript
基于JavaScript实现控制下拉列表
2020/05/08 Javascript
微信小程序实现签到弹窗动画
2020/09/21 Javascript
jQuery实现图片切换效果
2020/10/19 jQuery
Ant Design的可编辑Tree的实现操作
2020/10/31 Javascript
Python 检查数组元素是否存在类似PHP isset()方法
2014/10/14 Python
在Python的Flask框架中实现全文搜索功能
2015/04/20 Python
利用python实现简单的邮件发送客户端示例
2017/12/23 Python
服装设计专业毕业生推荐信
2013/11/09 职场文书
学校司机岗位职责
2013/11/14 职场文书
行政管理毕业生自荐信
2014/02/24 职场文书
经典禁毒标语
2014/06/16 职场文书
关于长城的导游词
2015/01/30 职场文书
行为规范主题班会
2015/08/13 职场文书
vue backtop组件的实现完整代码
2021/04/07 Vue.js
《暗黑破坏神2:重制版》本周进行第一轮A测 目前可官网进行申请报名
2021/04/07 其他游戏
CSS的calc函数用法小结
2022/06/25 HTML / CSS