ES6 const,用于在JavaScript中创建对象原型;这是一种模式吗



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

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

示例:

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提供了这些:

  1. 无法重新分配初始定义的对象。(只读)
  2. 可以重新指定初始对象的属性
  3. 可以将新特性添加到初始对象中

这些非常适合类定义

另一方面,有两种可供选择的方法来声明一个值:varlet。两者都不能提供只读引用。此外,var没有提供块作用域声明。当然,您可以使用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;
};

相关内容

最新更新