sor*_*ous 4 javascript ecmascript-6
我经常看到const
用于创建基础对象.
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)
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
提供这些:
这些非常适合课程定义!
另一方面,声明一个值有两种选择:var
和let
.两者都不能提供只读引用.也var
没有提供一个块范围声明.当然你可以使用var
或let
.这是您的选择和用法.
同样在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)
归档时间: |
|
查看次数: |
542 次 |
最近记录: |