浅谈nodejs中的类定义和继承的套路

2020-06-17 05:43:15易采站长站整理

javascript是一门极其灵活的语言。

灵活到你无法忍受!

我个人喜欢强类型的语言,例如c/c++,c#等。

但是js代表着未来,所以需要学习。

js中类定义以及继承有n多种方式,现在来学习一下nodejs类定义以及继承的固定套路。

套路1. 在构造函数(constructor)中总是使用instanceof操作符:


function Base() {
if (!(this instanceof Base)) {
return new Base();
}
}

上述代码的含义就是: 如果Base这个函数调用时没有使用new操作符,则会自动调用new操作符,返回Base的实例

套路2. 所有成员变量定义在构造函数(constructor)中


function Base() {
if (!(this instanceof Base)) {
return new Base();
}

//开始成员变量定义
this.className = "Base";
}

套路3. 所有的成员方法以函数表达式方式定义在原型(prototype)中【为什么要这样,其原因在套路4中的inherits源码注释中】


Base.prototype.printClassName = function(){
console.log(this.className);
}

调用如下:


var base = Base(); //不使用new操作符,直接进行函数调用,自动调用new操作符
console.log(base.className);
base.printClassName();

套路4. 使用util.inherits(子类,父类)进行原型(prototype)继承

先来看一下inherits的源码:


var inherits = function(ctor, superCtor) {
//严格相等测试:undefined/null
//子类构造函数必须存在
if (ctor === undefined || ctor === null)
throw new TypeError('The constructor to "inherits" must not be ' +
'null or undefined');
//严格相等测试:undefined/null
//父类构造函数必须存在
if (superCtor === undefined || superCtor === null)
throw new TypeError('The super constructor to "inherits" must not ' +
'be null or undefined');

//要点: 如果要继承的话,父类必须要有prototype对象
//这也是为什么将所有成员方法都定义在prototype对象中!!!
if (superCtor.prototype === undefined)
throw new TypeError('The super constructor to "inherits" must ' +
'have a prototype');

//让子类构造函数对象增加一个super_指针,指向父类,这样就形成继承链
ctor.super_ = superCtor;

//调用Object.setPrototypeOf(子类的prototype,父类的prototype)
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};

Object.setPrototypeOf : 该链接可以了解一下setPrototypeOf方法,非常简单,其Polyfill如下: