详解详解ES6中中class的实现原理的实现原理
一、在一、在ES6以前实现类和继承以前实现类和继承
实现类的代码如下:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.speakSomething = function () {
console.log("I can speek chinese");
};
实现继承的代码如下:一般使用原型链继承和call继承混合的形式
function Person(name) {
this.name = name;
}
Person.prototype.showName = function () {
return `名字是:${this.name}`;
};
function Student(name, skill) {
Person.call(this, name);//继承属性
this.skill = skill;
}
Student.prototype = new Person();//继承方法
二、二、ES6使用使用class定义类定义类
class Parent {
constructor(name,age){
this.name = name;
this.age = age;
}
speakSomething(){
console.log("I can speek chinese");
}
}
经过babel转码之后
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var Parent = function () {
function Parent(name, age) {
_classCallCheck(this, Parent);
this.name = name;
this.age = age;
}
_createClass(Parent, [{
key: "speakSomething",
value: function speakSomething() {
console.log("I can speek chinese");
}
}]);
return Parent;
}();