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 相关文章推荐
调用js时ie6和ie7,ff的区别
Aug 19 Javascript
ext jquery 简单比较
Apr 07 Javascript
跨浏览器开发经验总结(四) 怎么写入剪贴板
May 13 Javascript
js判断两个日期是否相等的方法
Sep 10 Javascript
fmt:formatDate的输出格式详解
Jan 09 Javascript
JS实现div居中示例
Apr 17 Javascript
JS选项卡动态替换banner图片路径的方法
May 11 Javascript
关于List.ToArray()方法的效率测试
Sep 30 Javascript
jQuery动态操作表单示例【基于table表格】
Dec 06 jQuery
layer ui插件显示tips时,修改字体颜色的实现方法
Sep 11 Javascript
解决vue项目中出现Invalid Host header的问题
Nov 17 Javascript
原生jQuery实现只显示年份下拉框
Dec 24 jQuery
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
模仿OSO的论坛(二)
2006/10/09 PHP
PHP 加密与解密的斗争
2009/04/17 PHP
PHP中for与foreach的区别分析
2011/03/09 PHP
ThinkPHP模板判断输出Present标签用法详解
2014/06/30 PHP
php上传图片并压缩的实现方法
2015/12/22 PHP
php把字符串指定字符分割成数组的方法
2018/03/12 PHP
详解php协程知识点
2018/09/21 PHP
PHP crypt()函数的用法讲解
2019/02/15 PHP
editable.js 基于jquery的表格的编辑插件
2011/10/24 Javascript
基于jquery实现拆分姓名的方法(纯JS版)
2013/05/08 Javascript
禁止选中文字兼容IE、Chrome、FF等
2013/09/04 Javascript
简单实用的反馈表单无刷新提交带验证
2013/11/15 Javascript
jquery实现浮动的侧栏实例
2015/06/25 Javascript
详解Node.js模块间共享数据库连接的方法
2016/05/24 Javascript
JS继承之借用构造函数继承和组合继承
2016/09/07 Javascript
NPM 安装cordova时警告:npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to
2016/12/20 Javascript
js装饰设计模式学习心得
2018/02/17 Javascript
Angular通过指令动态添加组件问题
2018/07/09 Javascript
Node.JS在命令行中检查Chrome浏览器是否安装并打开指定网址
2019/05/21 Javascript
浅谈TypeScript 用 Webpack/ts-node 运行的配置记录
2019/10/11 Javascript
javascript实现简单页面倒计时
2021/03/02 Javascript
手写Vue2.0 数据劫持的示例
2021/03/04 Vue.js
[55:45]DOTA2上海特级锦标赛D组败者赛 Liquid VS COL第一局
2016/02/28 DOTA
python计算N天之后日期的方法
2015/03/31 Python
使用Python的Bottle框架写一个简单的服务接口的示例
2015/08/25 Python
Python爬取十篇新闻统计TF-IDF
2018/01/03 Python
python2.7安装图文教程
2018/03/13 Python
利用python提取wav文件的mfcc方法
2019/01/09 Python
如何在网站上添加谷歌定位信息
2016/04/16 HTML / CSS
美国照明、家居装饰和家具购物网站:Bellacor
2017/09/20 全球购物
加拿大时装零售商:Influence U
2018/12/22 全球购物
美团网旗下网上订餐平台:美团外卖
2020/03/05 全球购物
毕业生幼师求职自荐信
2013/10/01 职场文书
银行出纳岗位职责
2013/11/25 职场文书
计算机软件个人的自荐信范文
2013/12/01 职场文书
面试中canvas绘制图片模糊图片问题处理
2022/03/13 Javascript