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

sor*_*ous 4 javascript ecmascript-6

我经常看到const用于创建基础对象.

  1. 这是一种模式吗?
  2. 如果是,有什么好处?

这里的例子:

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

const waffle = Object.create(food);
waffle.init('waffle');
console.log(waffle.type);
Run Code Online (Sandbox Code Playgroud)

yka*_*gol 5

const声明只读参考.如果使用声明,则无法更改该值const.请参阅MDN的文档:

const声明创建对值的只读引用.它并不意味着它拥有的值是不可变的,只是不能重新赋值变量标识符.

例如:

const x = {a:2};//declaration. 
x={b:3};//This statement throws an exception
x.c=4;//This is ok!
Run Code Online (Sandbox Code Playgroud)

所以,const提供这些:

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

这些非常适合课程定义!

另一方面,声明一个值有两种选择:varlet.两者都不能提供只读引用.也var没有提供一个块范围声明.当然你可以使用varlet.这是您的选择和用法.

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

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
Run Code Online (Sandbox Code Playgroud)

巴贝尔翻译像这样(通过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;
};
Run Code Online (Sandbox Code Playgroud)