ES6:class的定义与继承,从ES5转换成ES6
时间: 2024-02-17 08:03:57 浏览: 123
ES6引入了class关键字来定义类,以取代ES5中使用构造函数和原型链的方式。一个最基本的class定义如下所示:
```
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise');
}
}
let cat = new Animal('cat');
cat.speak(); // 输出: cat makes a noise
```
ES6中使用`extends`关键字实现继承,子类使用`super`关键字调用父类的构造函数和方法。一个最基本的继承示例如下:
```
class Dog extends Animal {
constructor(name) {
super(name); // 调用父类的构造函数
}
speak() {
console.log(this.name + ' barks');
}
}
let dog = new Dog('dog');
dog.speak(); // 输出: dog barks
```
使用Babel等工具可以将ES6的class定义转换成ES5的构造函数和原型链实现方式。转换后的代码如下:
```
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Animal = function Animal(name) {
_classCallCheck(this, Animal);
this.name = name;
};
Animal.prototype.speak = function () {
console.log(this.name + ' makes a noise');
};
var Dog = function (_Animal) {
_inherits(Dog, _Animal);
function Dog(name) {
_classCallCheck(this, Dog);
return _possibleConstructorReturn(this, (Dog.__proto__ || Object.getPrototypeOf(Dog)).call(this, name));
}
_createClass(Dog, [{
key: 'speak',
value: function speak() {
console.log(this.name + ' barks');
}
}]);
return Dog;
}(Animal);
```
阅读全文