gpt4 book ai didi

javascript - ES6 const 用于在 JavaScript 中创建对象原型(prototype);这是一种模式吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:06 28 4
gpt4 key购买 nike

我经常看到 const 被用来创建一个基础对象。

  1. 这是一种模式吗?
  2. 如果是,优势是什么?

Example from here :

const food = {
init: function(type) {
this.type = type;
}
}

const waffle = Object.create(food);
waffle.init('waffle');
console.log(waffle.type);

最佳答案

const 声明一个只读引用。如果用 const 声明,则不能更改该值。请参阅 MDN 中的文档:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

例如:

const x = {a:2};//declaration. 
x={b:3};//This statement throws an exception
x.c=4;//This is ok!

因此,const 提供了这些:

  1. 不能重新分配初始定义的对象。(只读)
  2. 可以重新分配初始对象的属性。
  3. 可以向初始对象添加新属性。

这些非常适合类定义!

另一方面,有两种方法可以声明一个值:varlet。两者都不能提供只读引用。此外,var 不提供 block 作用域声明。当然,您可以使用 varlet。这是您的选择和用途。

同样在 ES6 中,您可以定义这样的类(来自 MDN 的资源):

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

Babel像这样翻译它(通过使用 var):

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Polygon = function Polygon(height, width) {
_classCallCheck(this, Polygon);

this.height = height;
this.width = width;
};

关于javascript - ES6 const 用于在 JavaScript 中创建对象原型(prototype);这是一种模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37088188/

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