实现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 ...
随机推荐
- Java基础教程——Math类
Math Java这种级别的编程语言怎么可能没有数学相关的操作呢? java.lang.Math类提供了基本数学运算的方法. 该类是final的,说明不能被继承. 该类的构造方法是私有的(privat ...
- jupyter notebook 安装记录
conda install jupyterconda install jupyter_nbextensions_configuratorconda install jupyter_contrib_nb ...
- 原创题目 白银之春 Problem and Solution
白银之春 Solution 比赛用题面.题解.标程和数据生成器都挂在 git@github.com:sun123zxy/spring.git 上. Problem 白银之春 (spring.cpp/. ...
- python核心高级学习总结6------面向对象进阶之元类
元类引入 在多数语言中,类就是一组用来描述如何生成对象的代码段,在python中同样如此,但是在python中把类也称为类对象,是的,你没听错,在这里你只要使用class关键字定义了类,其解释器在执行 ...
- 第8.11节 Python类中记录实例变量属性的特殊变量__dict__
一. 语法释义 调用方法:实例. __dict__属性 __dict__属性返回的是实例对象中当前已经定义的所有自定义实例变量的名和值,用字典存储,每个元素为一个"实例变量名:值" ...
- PyQt(Python+Qt)学习随笔:QTabWidget选项卡部件的tabBar、count、indexOf方法
老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 QTabWidget的每个选项卡都有一个对应的页面部件对象,可用通过count方法获取选项卡个数,可 ...
- 第15.7节 PyQt入门学习:PyQt5应用构建详细过程介绍
一. 引言 在上节<第15.6节 PyQt5安装与配置>结束了PyQt5的安装和配置过程,本节将编写一个简单的PyQt5应用,介绍基本的PyQt5应用的文件组成及相关工具的使用. 本节的应 ...
- 安装虚拟机(centos7)
安装VMware 15 这里就不介绍VMware如何安装了,可以自行百度安装. 准备centos7镜像 我选择的是网易的镜像源,地址是:http://mirrors.163.com/centos/7/ ...
- HTML 实战生成一张页面
1 HTML简介 1.1 解释 HTML是用来描述网页的一种语言. HTML即超文本标记语言(Hyper Text Markup Language): HTML不是一种编程语言,而是一种标记语言(ma ...
- flask中migrate和scipt进行连用
近期态度消极了,并且还忙着学php,所以可能flask框架的进度不会像之前那么快了.但是还是要保证跟之前高的质量滴.