gpt4 book ai didi

javascript - ECMAScript 在其第六版中是否已经停止使用基于原型(prototype)的编程语法?

转载 作者:行者123 更新时间:2023-12-02 15:20:32 24 4
gpt4 key购买 nike

我是 JavaScript 的 ECMAScript5 语法的忠实粉丝,在我看来,这主要是因为这使得它在遵循相对传统的编程风格和语法的其他面向对象编程语言中独一无二。

不确定 ECMAScript6 是否仍支持 ECMAScript5 语法,即是否向后兼容。但是,是否有任何理由将语法(尤其是在 JavaScript 中定义类的基于原型(prototype)的方法(更不用说继承等))替换为更传统的语法(如大多数面向对象的语法)?编程语言)?

为了举例说明语法更改,根据 ECMAScript5,您可以在 JavaScript 中定义一个 person 类:

// ES5 class definition of a Person
function Person (name) {
this.name = name;
}

//adding methods or properties to the Person prototype
Person.prototype.walk = function(){
console.log(this.name + ' is walking');
}

与上面 ES6 中的实现相同:

class Person {
constructor(name) {
this.name = name;
}

walk() {
console.log(this.name + ' is walking.');
}
}

我问这个问题,是因为我相信,对于某些程序员来说,由于过于习惯旧的风格,转回传统语法可能一开始会出现问题。那么为什么首先会带来如此巨大的变化呢?

任何信息都将受到高度赞赏。

最佳答案

No.

JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax is not introducing a new object-oriented inheritance model to JavaScript. JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance.

关于javascript - ECMAScript 在其第六版中是否已经停止使用基于原型(prototype)的编程语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34127113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com