更新时间:2023-11-05 23:24:40
这几乎完全取决于你是否。新的类
的东西大多只是语法糖。 (但是,你知道那种好的糖)。
此外,将会是一个OOP的概念,或者它仍然是一个 JavaScript对象概念'?
我们一直拥有相同的原型继承,只需更清晰,更方便的语法和派生自 Array
和错误
(您不能在ES5及更早版本中)。
这是否意味着我无法使用.prototype修改它?
不,您一旦创建了类,您仍然可以在类的构造函数上修改原型
对象。例如,这是完全合法的:
class Foo {
constructor(name){
this.name =名字
}
test1(){
console.log(test1:name =+ this.name);
}
}
Foo.prototype.test2 = function(){
console.log(test2:name =+ this.name);
};
有没有关于速度的好处?
通过为此提供一个特定的成语,我认为这是可能的,引擎可能能够做一个更好的工作优化。但是他们非常善于优化,我不会指望有显着差异。
为什么要使用ES6类? p>
您可以选择的原因:
更容易(而且更容易出错)使用新的语法来设置继承层次结构,而不是旧的。
class
没有使用 new
与构造函数的错误(如果这个
不是一个构造函数抛出异常对于构造函数的有效对象)
调用父原型的方法版本比旧的( super.method()
而不是 ParentConstructor.prototype.method.call(this)
或 Object.getPrototypeOf(Object。 getPrototypeOf(本))。您可以从
Array派生
。$> $ / $ >(jQuery可能已经这样做了,如果Resig启动它是可能的)和错误
。
这是一个层次结构的语法比较:
// ES6
class Person {
constructor(first,last){
this.first = first;
this.last = last;
}
personMethod(){
// ...
}
}
类员工扩展Person {
构造函数(first,last,position){
super(first,last);
this.position = position;
}
employeeMethod(){
// ...
}
}
class Manager扩展Employee {
构造函数(first,last,position,department){
super(first,last,position);
this.department = department;
}
personMethod(){
const result = super.personMethod();
// ...使用`result`为某事...
返回结果;
}
managerMethod(){
// ...
}
}
vs。
// ES5
var Person = function(first,last){
if(!(this instanceof Person)){
throw new Error(Person is a constructor function,use new with it);
}
this.first = first;
this.last = last;
};
Person.prototype.personMethod = function(){
// ...
};
var Employee = function(first,last,position){
if(!(this instanceof Employee)){
throw new Error(Employee is a constructor function,use新的);
}
Person.call(this,first,last);
this.position = position;
};
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.employeeMethod = function(){
// ...
};
var Manager = function(first,last,position,department){
if(!(this instanceof Manager)){
throw new Error(Manager是一个构造函数,用新的);
}
Employee.call(this,first,last,position);
this.department = department;
};
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor = Manager;
Manager.prototype.personMethod = function(){
var result = Employee.prototype.personMethod.call(this);
// ...使用`result`为某事...
返回结果;
};
Manager.prototype.managerMethod = function(){
// ...
};