es6继承 vs js原生继承(es5)

时间:2024-01-10 21:27:02

最近在看es2015的一些语法,最实用的应该就是继承这个新特性了。比如下面的代码:

 $(function(){
class Father{
constructor(name, age){
this.name = name;
this.age = age;
} show(){
console.log(`我叫:${this.name}, 今年${this.age}岁`);
}
};
class Son extends Father{}; let son = new Son('金角大王', 200);
son.show();//return 我叫:金角大王, 今年200岁 });

这是一个最简单的继承。在Son类中并没有任何的自己的属性和方法,来看一下f12中的结构

es6继承 vs js原生继承(es5)

也是不例外的使用了原型链来实现的继承,那么在es5中如果要实现这个继承应该怎么做?

使用babel把这段代码翻译成es5的语法,发现代码如下:

 "use strict";

 var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

 function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

 function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

 /**
* Created by liuyc14 on 2016/6/28.
*/ var Father = function () {
function Father(name, age) {
_classCallCheck(this, Father); this.name = name;
this.age = age;
} _createClass(Father, [{
key: "show",
value: function show() {
console.log("我叫:" + this.name + ", 今年" + this.age + "岁");
}
}]); return Father;
}(); ; var Son = function (_Father) {
_inherits(Son, _Father); function Son() {
_classCallCheck(this, Son); return _possibleConstructorReturn(this, Object.getPrototypeOf(Son).apply(this, arguments));
} return Son;
}(Father); ;

这些是babel编译完成后生成的es5语法的实现代码,看起来多了很多东西。

不着急,挑出几个重点来看一下(以后的例子都使用es5语法

1. _createClass 方法,创建一个类,用到了defineProperties方法,就是给第一个参数的target对象,附加所有第二个参数的属性

2. _inherits 方法,实现继承的核心,用到了Object.create 和 Object.setPrototypeOf 方法

Object.create 方法:

这个方法接受两个参数,第一个参数为要继承的对象,第二参数为附加属性,返回一个创建后的对象。

举个例子:

 function Father(name, age){
this.name = name;
this.age = age;
} Father.prototype.show = function () {
console.log('我叫:' +this.name+', 今年'+this.age+'岁');
}; var obj = Object.create(Father.prototype);
console.log(obj.name); //return undefined
obj.show(); // return 我叫:undefined, 今年undefined岁

es6继承 vs js原生继承(es5)

es6继承 vs js原生继承(es5)

上面这个例子中,使用create方法,创建了一个obj对象,而且这个对象继承了Father.prototype对象的属性。(只有一个show方法,并没有 name 和 age 属性)

看到了这个作用以后,我们就可以使用create方法来实现es5的继承了

 function Father(name, age){
this.name = name;
this.age = age;
} Father.prototype.show = function () {
console.log('我叫:' +this.name+', 今年'+this.age+'岁');
}; function Son(name, age){
Father.call(this, name, age);
}
Son.prototype = Object.create(Father.prototype);
Son.prototype.constructor = Son;
Son.prototype.show = function () {
console.log('我是子类,我叫' + this.name + ', 今年' + this.age + '岁了');
};
var s = new Son('银角大王', 150); //return 我是子类,我叫银角大王, 今年150岁了
s.show();

上面的Son类在定义时,使用Father.call来继承Father的实例属性,使用Object.create方法来继承Father的原型,这样就完整的实现了继承,来看一下分析图

es6继承 vs js原生继承(es5)

Son的实例s,在原型中有自己的show方法,再往上查找Father的原型,还可以看到show的原型,很清晰的层次结构

es6继承 vs js原生继承(es5)

其实我们也可以不使用Object.create方法,使用Object.setPrototypeOf 方法来代替,达到同样的效果

把之前例子里第13行代码由

Son.prototype = Object.create(Father.prototype); =>
Object.setPrototypeOf(Son.prototype, Father.prototype);

这两行代码的效果是一样的,第二种方法更直观一些,就是把Son.prototype.__proto__ = Father.prototype 这样。

最后一个问题,我们如何才能向C#或者java里那样,在子类型中调用父类的方法呢?比如Son.prototype.show=function(){super.show()}这样

可以使用Object.getPrototypeOf(Son.prototype)方法来获取原型链的上一级,这样就可以获取到Father.prototype对象了,然后调用show()方法

 Son.prototype.show = function () {
Object.getPrototypeOf(Son.prototype).show();
console.log('我是子类,我叫' + this.name + ', 今年' + this.age + '岁了');
};

但是调用Son的show方法,会log出: 我叫:undefined, 今年undefined岁; 我是子类,我叫银角大王, 今年150岁了

为什么会有undefined?看看刚才我们的f12结构图,Father.prototype中是没有name 和 age 属性的,那么怎么办?使用call方法啊!

下面贴出完整的类继承实现代码:

 function Father(name, age){
this.name = name;
this.age = age;
} Father.prototype.show = function () {
console.log('我叫:' +this.name+', 今年'+this.age+'岁');
}; function Son(name, age){
Father.call(this, name, age);
}
Object.setPrototypeOf(Son.prototype, Father.prototype);
Son.prototype.constructor = Son;
Son.prototype.$super = Object.getPrototypeOf(Son.prototype);//使用$super属性来指向父类的原型
Son.prototype.show = function () {
this.$super.show.call(this);
console.log('我是子类,我叫' + this.name + ', 今年' + this.age + '岁了');
};
var s = new Son('银角大王', 150);
s.show();

OK,今天的总结写完了,跟流水账一样,大家凑活看吧