例如,说我有他的功能:
var person = (function(){
var age = "will"
function shoutAge(){
alert(age)
}
return {
shoutAge
}
})()
Run Code Online (Sandbox Code Playgroud)
创建完成后,我可以这样做:
person.age = 45;
Run Code Online (Sandbox Code Playgroud)
当然,这不是人的范围内的年龄,但这可能会引起混淆.
我把它更改为使用const:
const person = (function(){
var age = "will"
function shoutAge(){
alert(age)
}
return {
shoutAge
}
})()
Run Code Online (Sandbox Code Playgroud)
但我仍然可以添加自定义属性.
我误解了const的用途,你无法重新分配变量,但你可以很好地添加属性.
但是有没有办法让它不可编辑,或者是某些因某些原因不应该做的事情?
一种选择是Object.freeze在返回之前在对象上使用,其中:
防止新属性被添加到其中; 防止删除现有属性; 并且可以防止现有属性或其可枚举性,可配置性或可写性被更改,还可以防止原型被更改.
'use strict';
var person = (function() {
var age = "will"
function shoutAge() {
console.log(age)
}
return Object.freeze({
shoutAge
})
})();
person.shoutAge();
person.foo = 'foo';Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |