gpt4 book ai didi

javascript - ECMA6 是否取消了使用原型(prototype)语法作为 JavaScript 中的最佳实践?

转载 作者:行者123 更新时间:2023-11-29 15:34:47 24 4
gpt4 key购买 nike

例子,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

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. JS classes provide a much simpler and clearer syntax to create objects and dealing with inheritance.

这是否意味着我应该停止在我的开发中使用语言术语 prototype ,当 ECMA6 是最终的并且使用新的语法糖像这样制作时。我相信除此之外它们是相同的(来自同一页面):

// unnamed
var Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

// named
var Polygon = class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
};

另一方面,我看到了这一点,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

var obj = {
foo() {},
bar() {}
};

这一切如何组合在一起?我将如何处理 var myObj?它能像其他语言一样拥有构造函数和方法 foo()bar() 吗?这是允许的吗?

var myObj = class myObj {
contructor(height, width){
this.height=height;
this.width=width;
},
foo(this.height) {alert('the height is ' + this.height)},
bar(this.height, this.width) {
alert('the width is ' + this.width);
var something = this.height + 5;
alert('the height is : ' + something);

}
};

var determine_something = new myObj(50,60);
determine_something.bar;
determine_something.foo;

(这在我试过的 ECMA6 沙箱中不起作用)

这没有错误,但是 this.height 是未定义的:

var myObj = class {
contructor(height, width){
this.height=height;
this.width=width;
}
foo() {
alert('the height is ' + this.height);
}

};

var determine_something = new myObj(50,60);
determine_something.foo();

编辑:如果我不使用 prototype,并且我想添加一个新方法,我该如何使用新语法来实现?

最佳答案

这是固定/优化的版本:

class MyObj {
contructor(height, width){
this.height = height;
this.width = width;
}

foo() {
alert(`the height is ${this.height}`)
}

bar() {
alert(`the width is ${this.width}`);
const something = this.height + 5;
alert(`the height is : ${something}`);
}
};

const determine_something = new MyObj(50,60);
determine_something.bar();
determine_something.foo();

关于javascript - ECMA6 是否取消了使用原型(prototype)语法作为 JavaScript 中的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30518180/

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