实现JavaScript继承
使用TypeScript或者ES2015+标准中的extends关键字是很容易实现继承的,但这不是本文的重点。JS使用了基于原型(prototype-based)的继承方式,extends只是语法糖,本文重点在于不使用extends来自己实现继承,以进一步理解JS中的继承,实际工作中肯定还是要优先考虑使用extends关键字的。
原型 & 原型链
原型用于对象属性的查找。画出下面代码中的原型链图示:
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
get getName(): string {
return this._name;
}
}
let person = new Person("xfh");

图中,__proto__表示实例的原型对象,prototype表示构造函数的原型对象。不再推荐使用__proto__,将来可能会被废弃,可使用Object.getPrototypeOf()来获取对象的原型。
关于原型/链,记住以下几点:
原型链的终点是null,从这个角度,可以将null看作所有Object的基类
实例的原型对象和它构造函数的原型对象是同一个对象(比较拗口)
所有的函数(包括构造函数及Function自身)都是Function的实例
函数是普通的对象,只是具备了可调用(callable)功能 ,想到了Python中的类装饰器,也是具备了可调用功能的普通类
所有的对象终归是Object的实例,即Object位于所有对象的原型链上
// 原型链的终点是null
Object.getPrototypeOf(Object.prototype)===null // true
Object.prototype instanceof Object // false
// 实例和构造函数的原型对象是同一个对象
Object.getPrototypeOf(Function)===Function.prototype // true
// 所有的函数(包括构造函数及Function自身)都是Function的实例
Function instanceof Function // true,Function是自己的实例
Object instanceof Function // true,构造函数是Function的实例
// 所有的对象终归是Object的实例,即Object位于所有对象的原型链上
Function.prototype instanceof Object // true
Function instanceof Object // true
Object instanceof Object // true
typeof操作符与instanceof`关键字的区别如下:
Keep in mind the only valuable purpose of
typeofoperator usage is checking the Data Type. If we wish to check any Structural Type derived from Object it is pointless to usetypeoffor that, as we will always receive"object". The indeed proper way to check what sort of Object we are using isinstanceofkeyword. But even in that case there might be misconceptions.
实现继承
JS中对象成员分为三类:实例、静态、原型。实例成员绑定到具体实例上(通常是this上),静态成员绑定到构造函数上,原型成员就存在原型对象上:
/**
* 从基类继承成员
* @param child 子类构造函数或实例
* @param base 基类构造函数或实例
*/
function inheritMembers(child, base) {
let ignorePropertyNames = ["name", "caller", "prototype", "__proto__", "length", "arguments"];
let propertyNames = Object.getOwnPropertyNames(base);
for (let propertyName of propertyNames) {
if (ignorePropertyNames.includes(propertyName)) {
continue;
}
let descriptor = Object.getOwnPropertyDescriptor(base, propertyName);
if (!descriptor) {
continue;
}
Object.defineProperty(child, propertyName, descriptor);
}
}
/**
* 从基类继承原型及静态成员
* @param thisCtor 子类构造函数
* @param baseCtor 基类构造函数
*/
function inheritSharedMembers(thisCtor, baseCtor) {
if (typeof thisCtor !== "function" || typeof baseCtor !== "function") {
throw TypeError("参数必须是函数:thisCtor,baseCtor");
}
// 继承原型成员
thisCtor.prototype = Object.create(baseCtor.prototype);
thisCtor.prototype.constructor = thisCtor;
// 继承静态成员
inheritMembers(thisCtor, baseCtor);
}
/**
* 调用子类及父类构造函数创建子类实例,并继承父类实例成员(这也是调用父类构造函数的原因)
* @param thisInstance 子类实例
* @param baseInstance 父类实例
*/
function createInstance(thisInstance, baseInstance) {
inheritMembers(thisInstance, baseInstance);
return thisInstance;
}
// 构造函数
function Animal(tag) {
// 实例属性
this.tag = tag;
}
// 静态方法,需通过构造函数来调用
Animal.bark = function () {
console.log("static func, this= " + this + ", typeof this=" + typeof this);
};
// 原型方法,需通过实例来调用
Animal.prototype.getInfo = function () {
console.log("property func, tag:" + this.tag);
};
function Dog(name = null) {
this.name = name ?? "default";
}
// 添加子类原型方法
Dog.prototype.dogBark = function () {
console.log("dog bark");
};
// 继承父类原型及静态成员
inheritSharedMembers(Dog, Animal);
var animal = new Animal("animal");
Animal.bark();
// TypeError: animal.bark is not a function
// animal.bark();
animal.getInfo();
// property getInfo not exist on type 'typeof Animal'
// Animal.getInfo();
let dog = createInstance(new Dog("dog"), new Animal("dog"));
dog.getInfo();
dog.dogBark();
Dog.bark();
console.log(dog.name);
最后使用v4.1.3版本的TS,编译为ES5版本的JS,看看TS背后是如何实现继承的:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
// 只能在构造函数中使用this关键字
this.name = name;
this.age = age;
}
// 静态方法中调用本类中的另一个静态方法时,可以使用this.methodName的形式
// 在外部调用时只能类名.方法名的形式,所以此时方法内部,this是指向构造函数的
// 即,this.methodName等价于类名.方法名
static static_method() {
// 这里this指向Person类,typeof this=function
// 可以看出class Person本质上是构造函数,class只是语法糖
console.log(`static method, this=${this}, typeof this=${typeof this}`);
}
}
// 使用extends继承
class Chinese extends Person {
constructor(name: string, age: number) {
// 必须调用父类构造函数,且需要在子类构造函数使用this关键字之前调用,否则会产生错误:
// A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.
super(name, age);
}
sayHello() {
console.log(`I'm ${this.name}, I'm ${this.age} years old.`)
}
}
let cn = new Chinese('xfh', 26);
cn.sayHello();
Chinese.static_method();
编译后代码如下:
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Person = /** @class */ (function () {
function Person(name, age) {
// 只能在构造函数中使用this关键字
this.name = name;
this.age = age;
}
// 静态方法中调用本类中的另一个静态方法时,可以使用this.methodName的形式
// 在外部调用时只能类名.方法名的形式,所以此时方法内部,this是指向构造函数的
// 即,this.methodName等价于类名.方法名
Person.static_method = function () {
// 这里this指向Person类,typeof this=function
// 可以看出class Person本质上是构造函数,class只是语法糖
console.log("static method, this=" + this + ", typeof this=" + typeof this);
};
return Person;
}());
// 使用extends继承
var Chinese = /** @class */ (function (_super) {
__extends(Chinese, _super);
function Chinese(name, age) {
// 必须调用父类构造函数,且需要在子类构造函数使用this关键字之前调用,否则会产生错误:
// A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties.
return _super.call(this, name, age) || this;
}
Chinese.prototype.sayHello = function () {
console.log("I'm " + this.name + ", I'm " + this.age + " years old.");
};
return Chinese;
}(Person));
var cn = new Chinese('xfh', 26);
cn.sayHello();
Chinese.static_method();
推荐阅读
JavaScript data types and data structures
实现JavaScript继承的更多相关文章
- javascript继承的三种模式
javascript继承一般有三种模式:组合继承,原型式继承和寄生式继承: 1组合继承:javascript最为广泛的继承方式通过原型链实现对原型属性和方法的继承,通过构造函数实现对实例属性的继承,同 ...
- javascript继承机制的设计思想(ryf)
我一直很难理解Javascript语言的继承机制. 它没有"子类"和"父类"的概念,也没有"类"(class)和"实例" ...
- 【读书笔记】javascript 继承
在JavaScript中继承不像C#那么直接,C#中子类继承父类之后马上获得了父类的属性和方法,但JavaScript需要分步进行. 让Brid 继承 Animal,并扩展自己fly的方法. func ...
- 图解JavaScript 继承
JavaScript作为一个面向对象语言,可以实现继承是必不可少的,但是由于本身并没有类的概念(不知道这样说是否严谨,但在js中一切都类皆是对象模拟)所以在JavaScript中的继承也区别于其他的面 ...
- JavaScript强化教程——Cocos2d-JS中JavaScript继承
javaScript语言本身没有提供类,没有其它语言的类继承机制,它的继承是通过对象的原型实现的,但这不能满足Cocos2d-JS引擎的要求.由于Cocos2d-JS引擎是从Cocos2d-x演变而来 ...
- [原创]JavaScript继承详解
原文链接:http://www.cnblogs.com/sanshi/archive/2009/07/08/1519036.html 面向对象与基于对象 几乎每个开发人员都有面向对象语言(比如C++. ...
- javascript继承(六)—实现多继承
在上一篇javascript继承—prototype最优两种继承(空函数和循环拷贝)(3) ,介绍了js较完美继承的两种实现方案,那么下面来探讨一下js里是否有多继承,如何实现多继承.在这里可以看看j ...
- javascript继承(五)—prototype最优两种继承(空函数和循环拷贝)
一.利用空函数实现继承 参考了文章javascript继承—prototype属性介绍(2) 中叶小钗的评论,对这篇文章中的方案二利用一个空函数进行修改,可以解决创建子类对象时,父类实例化的过程中特权 ...
- javascript继承(四)—prototype属性介绍
js里每一个function都有一个prototype属性,而每一个实例都有constructor属性,并且每一个function的prototype都有一个constructor属性,这个属性会指向 ...
- 【JavaScript】重温Javascript继承机制
上段时间,团队内部有过好几次给力的分享,这里对西风师傅分享的继承机制稍作整理一下,适当加了些口语化的描述,留作备案. 一.讲个故事吧 澄清在先,Java和Javascript是雷锋和雷峰塔的关系.Ja ...
随机推荐
- git的使用以及git和码云的连接
什么是git? Git是一个开源的分布式版本控制系统,可以有效.高速地处理从很小到非常大的项目版本管理.可以保存许多的历史版本,并且可以多人同时进行开发. 分布式版本控制系统 每个人拥有该项目 ...
- Bootstrap Blazor 组件介绍 Table (三)列数据格式功能介绍
Bootstrap Blazor 是一套企业级 UI 组件库,适配移动端支持各种主流浏览器,已经在多个交付项目中使用.通过本套组件可以大大缩短开发周期,节约开发成本.目前已经开发.封装了 70 多个组 ...
- Moviepy音视频开发:开发视频转gif动画或jpg图片exe图形化工具的案例
☞ ░ 前往老猿Python博文目录 ░ 一.引言 老猿之所以学习和研究Moviepy的使用,是因为需要一个将视频转成动画的工具,当时在网上到处搜索查找免费使用工具,结果找了很多自称免费的工具,但转完 ...
- 老猿学5G随笔:5G网元功能体NF以及NF之间的两种接口--服务化接口和参考点
一.5G功能体之间的接口类型 5G不同功能体之间提供了两种接口: 服务化接口:Service-basedinterface,这个是类似微服务化架构的服务注册和服务发现来实现的功能体对外暴露的接口,这种 ...
- Python正则运算符优先级re.findall('(.)*',"abc")、re.findall('(.*)',"abc")、re.findall('(.?)*',"abc")的执行结果的影响分析
我们分别执行三个语句: >>> re.findall('(.)*',"abc") ['c', ''] >>> re.findall('(.*)' ...
- Python妙用re.sub分析正则表达式匹配过程
声明:本文所使用方法为老猿自行研究并编码,相关代码版权为老猿所有,禁止转载文章,代码禁止用于商业用途! 在<第11.23节 Python 中re模块的搜索替换功能:sub及subn函数>介 ...
- 小程序使用动画时的 px 单位 转 rpx的方法
借助API wx.getSystemInfoSync(); 通过API可获取的值: // 在 iPhone6 下运行: var systemInfo = wx.getSystemInfoSync(); ...
- ARC109F - 1D Kingdom Builder
一行格子,其中小于\(0\)的格子为白色,大于\(n\)的格子为黑色,中间的格子颜色由题目给出. 有一些格子需要被标记.标记按照以下规则进行:选择一个颜色\(c\),找到一个未标记的 旁边有标记点的 ...
- libev的用法
本例是以linux环境c++的用法,ide用的是vs2019 一.libev的安装 我们采用的是apt-get方法(偷懒^_^),你也可以采用源码方式安装 sudo apt-get install l ...
- Echarts入门教程精简实用系列
引语:echarts.js是百度团队推出的一款用于图表可视化的插件,用于以图表的形式展现数据,功能强大,上手简单 1.从官方网站中下载所需的echarts.js文件,该文件因功能广泛,包体较大,可自行 ...