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>

猜你喜欢

转载自www.cnblogs.com/cmy1996/p/9108722.html