我假设因为javascript中的类只是语法,因此在某些时候将类转换为构造函数,所以我也假设他为引擎创建了额外的东西,是这是一个准确的假设吗?
//Class, is this slower then a constructor
class Employee{
constructor(name,job,weeklyPay,age){
this.name=name;
this.breed=breed;
this.age=age;
}
pay(){
console.log(this.name + ": was paid " + weeklyPay);
}
}
class Manager extends Employee{
constructor(){
this.reports=[];
}
addReport(report){
this.report.push(report);
}
removeReport(index){
this.report.splice(index,1);
}
}
//constructor, is this more performant then a class?
function Employee(name,job,weeklyPay,age){
this.name=name;
this.job=job;
this.weeklyPay=weeklyPay;
this.age=age;
}
Employee.prototype.pay=function(){
console.log(this.name + ": was paid " + weeklyPay);
}
function Manager(name,job,weeklyPay,age){
Employee.call(this,name,job,weeklyPay,age);
this.name=name;
this.job=job;
this.weeklyPay=weeklyPay;
this.age=age;
this.reports=[];
}
Manager.prototype=Object.create(Employee.prototype);
Manager.prototype.addReport=function(report){
this.reports.push(report);
}
Manager.prototype.removeReport=function(index){
this.reports.splice(index,1);
}
答案 0 :(得分:0)
不,这不准确。
我假设因为javascript中的类只是语法suger,所以类在某些时候被转换为构造函数
不是真的。两者都被转换为函数和对象的内部表示,但这是独立发生的。
我还假设他为引擎创造了额外的东西吗?
不,“额外的东西”意味着class
语法将被翻译成构造函数代码,然后像往常一样进行解析。这只是当您使用转换器时发生的情况,但肯定不是引擎如何做到这一点。
实际上,假设应该相反:class
语法更接近构造函数的内部表示,通过传递 intent 作为类使用它更容易优化比普通的function
需要额外的启发式算法。它更具说明性(不需要任何突变),并且在规范中设计为更容易编译(例如通过暗示严格模式)。