- Hands-On Machine Learning with JavaScript
- Burak Kanber
- 247字
- 2021-06-25 21:38:18
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.
- 會(huì)聲會(huì)影X5視頻剪輯高手速成
- Cinema 4D R13 Cookbook
- Dreamweaver CS3網(wǎng)頁(yè)設(shè)計(jì)50例
- MicroPython Projects
- 空間傳感器網(wǎng)絡(luò)復(fù)雜區(qū)域智能監(jiān)測(cè)技術(shù)
- Zabbix Network Monitoring(Second Edition)
- Prometheus監(jiān)控實(shí)戰(zhàn)
- 人工智能技術(shù)入門(mén)
- JRuby語(yǔ)言實(shí)戰(zhàn)技術(shù)
- 大數(shù)據(jù):引爆新的價(jià)值點(diǎn)
- Learning Cassandra for Administrators
- Windows 7故障與技巧200例
- Keras Reinforcement Learning Projects
- Architectural Patterns
- 三維動(dòng)畫(huà)制作(3ds max7.0)