Technicalarticles
Car
和另一个继承自Car
的SportsCar
类。它们都具有make
和model
属性和start
方法,但SportsCar
还具有turbocharged
属性并覆盖start
方法:// "class" declaration
function Car(make, model) {
this.make = make;
this.model = model;
}
// the start method
Car.prototype.start = function() {
console.log('vroom');
}
// overriding the toString method
Car.prototype.toString = function() {
console.log('Car - ' + this.make + ' - ' + this.model);
}
// inheritance example
function SportsCar(make, model, turbocharged) {
Car.call(this, make, model);
this.turbocharged = turbocharged;
}
// actual inheritance logic
SportsCar.prototype = Object.create(Car.prototype);
SportsCar.prototype.constructor = SportsCar;
// overriding the start method
SportsCar.prototype.start = function() {
console.log('VROOOOM');
}
// Now testing the classes
var car = new Car('Nissan', 'Sunny');
car.start(); // vroom
console.log(car.make); // Nissan
var sportsCar = new SportsCar('Subaru', 'BRZ', true);
sportsCar.start(); // VROOOOM
console.log(car.turbocharged); // true
Car
(第2行)和SportsCar
(第18行)函数是构造函数。使用this
关键字定义属性,使用new
创建实例。如果您不熟悉prototype
,这是每个JS对象都必须委派常见行为的特殊属性。例如,原型为数组对象所具有的功能,你可能很熟悉:map
,forEach
,find
等原型为字符串具有的功能replace
,substr
等等。start
产生以下操作:
car
对象上的一个键值start
。car.prototype
上的一个键值start
。car.prototype
返回的start
功能,JS引擎立即执行。make
和model
属性的操作类似,只是它们直接在Car
对象上定义而不是在prototype
上定义。Object.create
。它接受一个对象并返回一个全新的对象,其原型设置为作为参数传递的对象。现在,如果JS引擎在sportsCar
对象或上找不到值sportsCar.prototype
,它将查询sportsCar.prototype.prototype
也就是Car
对象的原型。
class
关键字出现在JavaScript中。这样做是根据社区的众多要求完成的,因为人们对来自面向对象的语言感到不自在。但是他们忽略了一个重点。
JavaScript has no idea what classes are
function iAmAnObject() {}
console.log(iAmAnObject.name); // iAmAnObject
console.log(Object.keys(iAmAnObject)); // Array []
class
关键字如何工作?很高兴你问。您还记得前面的Car
和SportsCar
示例吗?好吧,class
关键字最重要的是语法糖。换句话说,类在概念上产生相同的代码,并且仅用于美学和可读性目的。正如我之前所承诺的,这是ES6中这些相同类的示例:class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
start() {
console.log('vroom');
}
toString() {
console.log(`Car - ${this.make} - ${this.model}`);
}
}
class SportsCar extends Car {
constructor(make, model, turbocharged) {
super(make, model);
this.turbocharged = turbocharged;
}
start() {
console.log('VROOOOM');
}
}
// Actual usage remains the same
var car = new Car('Nissan', 'Sunny');
car.start(); // vroom
console.log(car.make); // Nissan
var sportsCar = new SportsCar('Subaru', 'BRZ', true);
sportsCar.start(); // VROOOOM
console.log(car.turbocharged); // true
this
关键字紧密处理时,它可能会引入潜在的绑定问题,特别是如果您尝试将类方法作为回调传递给外部例程(您好,React devs)DO U LIKE?