Contents
class RealImg{
constructor(fileName){
this.fileName = fileName;
this.loadFromDisk()
}
display(){
console.log('display.....'+ this.fileName)
}
loadFromDisk(){
console.log('from disk.....'+ this.fileName)
}
}
class ProxyImg{
constructor(fileName){
this.realImg = new RealImg(fileName);
}
display(){
this.realImg.display()
}
}
//测试
let proxyImg = new ProxyImg('1.png')
proxyImg.display()
<div id="div1">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
<a href="#">a5</a>
</div>
var div1 = document.getElementById('div1');
div1.addEventListener('click',function (e) {
var target = e.target
if(target.nodeName ==='A'){
alert(target.innerHTML)
}
})
<div id="div1">
<a href="#">a1</a>
<a href="#">a2</a>
<a href="#">a3</a>
<a href="#">a4</a>
<a href="#">a5</a>
</div>
$('#div1').click(function () {
var _this = this
setTimeout(function () {
//直接$(this) 的话当前this 不是 $('#div1')
$(_this).addClass('red')
},1000)
})
//使用代理
$('#div1').click(function () {
setTimeout($.proxy(function () {
//直接$(this) 的话当前this 不是 $('#div1')
$(this).addClass('red')
},this),1000);
})
//定义一个real 对象
let star = {
name:'w候人兮猗',
age:22,
phone:'15955041111'
}
//定义一个代理
let agent = new Proxy(star,{
get:function (target,key) {
if(key === 'phone'){
//返回代理的电话
return '1123123'
}
if(key === 'price'){
//原对象不做这件事 返会的是代理的
return '120000'
}
return target[key]
},
set:function (target, key, value) {
if(key === 'customPrice'){
if(value < 10000){
alert('价格太低')
}else{
target[key] = value
return true
}
}
}
})
// 测试
console.log(agent.name)
console.log(agent.age)
console.log(agent.phone)
console.log(agent.price)
agent.customPrice = 15000000;
console.log(agent.customPrice)