JavaScript中this的一些练习

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.father {
width: 100px;
height: 100px;
background-color: red;
}
.child {
width: 20px;
height: 20px;
background-color: yellow
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
<script src="jquery-1.11.2.min.js"></script>
<script>
//on方法会向事件监听的处理函数传递一个参数 event.target 处理函数内部的this指向
// event.target 所以打印出来的this就是event.target 即<div class="child"></div>

// $('.child').on('click',function(){
// console.log(this); //<div class="child"></div>
// })


//事件委托,首先按字面的意思就能看你出来,是将事件交由别人来执行,
// 再联想到上面讲的事件冒泡,是不是想到了?对,
// 就是将子元素的事件通过冒泡的形式交由父元素来执行。
// 事件委托不仅实现相同了功能,而且大大减少了DOM操作。

//监听.father下的.child的点击事件
// $('.father').on('click','.child',function(){
// console.log(this); //<div class="child"></div>
// })
 
// $('.child')[0].on('click',function(){
// console.log(this);//<div class="child"></div>
// })

var app={
init:function(){ //init()里面的this指的是app
this.$father=$('.father'); //给app这个对象绑定一个属性$father
this.$child=$('.child');// 给app这个对象绑定一个属性$child
this.bind();//app.bind()
},
bind:function(){
var _this=this;//this指的是app

//监听.father点击事件 监听到click时 向this.sayHi传递了event.target
//即.father的dom对象<div class="father"><div class="child"></div></div>
this.$father.on('click',this.sayHi);

// 将_this.sayHello()改写为_this.sayHello.call(_this)
// sayHello在执行的时候 内部的this指向的app对象本身
this.$child.on('click',function(){
_this.sayHello();
})

//如果没有bind(this),this.sayBye会接受到传递的event.target即.child的dom对象
// 但此时手动绑定了this 而绑定的this与拒收的this是一致的 指代的是app对象
this.$child.on('click',this.sayBye.bind(this))
},
sayHi:function(){
console.log('sayHi',this)//<div class="father"><div class="child"></div></div>
},
sayHello:function(){
console.log('sayHello',this)//app
},
sayBye:function(){
console.log('sayBye',this)//app
}
}
app.init();
</script>
</body>
</html>

转载于:https://www.cnblogs.com/cmy1996/p/9108722.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值