1、对象内的属性和方法可以被外部调用到(可读可写):
var obj = {
ff:function(a){
console.log("ok,,,,"+a);
},
aa:1,
ff2:function(){
this.ff(this.aa)
}
}
image.png
2、而如果想和java的私有属性(private)那样,只提供给内部方法调用,外部只能通过调用方法间接访问内部私有变量,这该如何实现?
书中例子:
function Ninja(){
let skillLevel;
this.getSkillLevel = ()=> skillLevel;
this.setSkillLevel = value =>{
skillLevel = value;
};
}
const ninja = new Ninja();
ninja.setSkillLevel("hahahahahah");
ninja.getSkillLevel();//hahahahahah
image.png
这样实现了对skillLevel的保护,通过函数调用设置值或者获取值。
3、es5之后可以直接定义getter 和setter方法,简化了上述步骤
例子:
const ninjaCollection = {
ninjas:["Yoshi","Kuma","Hattori"],
get firstNinja(){
return this.ninjas[0];
},
set firstNinja(value){
this.ninjas[0] = value;
}
};
console.log(ninjaCollection.firstNinja);//Yoshi
ninjaCollection.firstNinja = "Bob";
console.log(ninjaCollection.firstNinja);//Bob
运行截图
image.png
es6中通过加入中间代理层实现保护原有对象。
const obj ={name :"zhangsan",age:33};
const proxyTest = new Proxy(obj,{get:(target,key)=>{console.log(key);return key in target?target[key]:"not found this value"}});
const proxyTest2 = new Proxy(obj,{get:(target,key)=>{console.log(key);return key in target?target[key]:"not found this value"},set:(target,key,value)=>{target[key] = value}})
const proxyTest3 = new Proxy(obj,{});
proxyTest3.age = 99;
obj//{name:"zhangsan",age:99}
运行截图⬇️
image.png
image.png
image.png
网友评论