官术网_书友最值得收藏!

Classes

One very welcome change in ES6 is the addition of classes and class inheritance. Previously, object-oriented programming in JavaScript required prototypical inheritance, which many developers found unintuitive, like the following ES5 example:

var Automobile = function(weight, speed) {
this.weight = weight;
this.speed = speed;
}
Automobile.prototype.accelerate = function(extraSpeed) {
this.speed += extraSpeed;
}
var RaceCar = function (weight, speed, boost) {
Automobile.call(this, weight, speed);
this.boost = boost;
}
RaceCar.prototype = Object.create(Automobile.prototype);
RaceCar.prototype.constructor = RaceCar;
RaceCar.prototype.accelerate = function(extraSpeed) {
this.speed += extraSpeed + this.boost;
}

In the preceding code, extending an object requires calling the parent class in the child's constructor function, creating a clone of the parent's prototype object, and overriding the parent's prototype constructor with the child's prototype constructor. These steps were seen as unintuitive and burdensome by most developers.

Using ES6 classes, however, the code will look like this:

class Automobile {
constructor(weight, speed) {
this.weight = weight;
this.speeed = speed;
}
accelerate(extraSpeed) {
this.speed += extraSpeed;
}
}
class RaceCar extends Automobile {
constructor(weight, speed, boost) {
super(weight, speed);
this.boost = boost;
}
accelerate(extraSpeed) {
this.speed += extraSpeed + this.boost;
}
}

The preceding syntax is more in line with what we'd expect from object-oriented programming, and also makes inheritance much simpler.

It's important to note that under the hood, ES6 classes still use JavaScript's prototypical inheritance paradigm. Classes are just syntactic sugar on top of the existing system, so there is no significant difference between these two approaches other than clean code.

主站蜘蛛池模板: 宜阳县| 永济市| 临夏市| 会理县| 蓝山县| 宜州市| 淄博市| 河东区| 巴马| 琼海市| 安达市| 井陉县| 色达县| 台中县| 大余县| 洪雅县| 和田市| 临汾市| 乌拉特后旗| 伊吾县| 乐清市| 进贤县| 兖州市| 夹江县| 桐柏县| 枝江市| 内黄县| 崇礼县| 兖州市| 疏勒县| 南宁市| 新泰市| 平塘县| 即墨市| 比如县| 富锦市| 丹凤县| 仙居县| 青州市| 华池县| 射洪县|