let api = (function(){
var obj = {
a:1,
b:2
}
return {
get(key){
return obj[key]
}
}
})()
问题: 要求修改闭包里 obj 对象的属性
破解方法之一:
// 破坏以上闭包的数据结构方法
// 可以在Object.prototype上定义新属性, 属性上放入get方法返回this对象
Object.defineProperty(Object.prototype,'newAPI',{
get(){
console.log(this)
return this
}
})
api.get('newAPI')['c'] = 3
api.get('c')
改进方法:
// 改进方式, 防止访问原型链属性
api = (function(){
var obj = {
a:1,
b:2
}
return {
get(key){
if(obj.hasOwnProperty(key)){
return obj[key]
}
}
}
})()