我经常看到const
被用来创建一个基础对象。
- 这是一种模式吗
- 如果是,优势是什么
示例:
const food = {
init: function(type) {
this.type = type;
}
}
const waffle = Object.create(food);
waffle.init('waffle');
console.log(waffle.type);
const
声明了一个只读引用。如果使用const
声明,则不能更改该值。参见MDN:的文档
const声明创建对某个值的只读引用。它并不意味着它所持有的值是不可变的,只是变量无法重新分配标识符。
例如:
const x = {a:2};//declaration.
x={b:3};//This statement throws an exception
x.c=4;//This is ok!
因此,const
提供了这些:
- 无法重新分配初始定义的对象。(只读)
- 可以重新指定初始对象的属性
- 可以将新特性添加到初始对象中
这些非常适合类定义
另一方面,有两种可供选择的方法来声明一个值:var
和let
。两者都不能提供只读引用。此外,var
没有提供块作用域声明。当然,您可以使用var
或let
。这是您的选择和使用。
同样在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;
};