有次面试遇到的,也是没说清楚具体的作用,感觉自己现在还是没有深刻的理解!
bind():绑定事件类型和处理函数到DOM element(父元素上)
live():绑定事件到根节点上,(document上)
Delegate(): 可动态添加事件,绑定到你指定的元素节点
下面就bind()方法做一个例子实验:(已测试)
window.onload = function(){
window.name = "window";
var newObject = {
name : "object",
sayGreeting : function(){
alert("now this is easy"+" "+this.name);
nestedGreeting = function (greeting){
alert(greeting+" "+this.name);
}.bind(this);
nestedGreeting("hello");
}
};
newObject.sayGreeting("hello");
}
这个程序的输出:
now this is easy object
hello object
当去掉红色部分bind()方法时输出第二个弹窗:hello window(想一下原因)
前面说过bind()方法绑定到父元素,也就是对象newObject上,this指的就是父类name值是object
如果去掉,嵌套函数nestedGreeting()对象的内部函数分离了,函数作用域变成了窗口对象的属性,name值为window
对于this的引用作用域没搞清楚,不知道到底作用哪个,有的说是就近,那这个例子中this就近谁呢,输出的怎么不一样,有大神能简单明了的说一下,不胜感激!!
最后提供一个页面倒计时展示bind():
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<style type="text/css">
#item {
font-size: 72pt;
margin: 70px auto;
width: 100px;
}
</style>
</head>
<body>
<div id = "item">
10
</div>
<script>
var theCounter = new Counter("item",10,0);
theCounter.countDown();
function Counter(id,start,finish){
this.count = this.start = start;
this.finish = finish;
this.id = id;
this.countDown = function (){
if(this.count ==this.finish){
this.countDown = null;
return;
}
document.getElementById(this.id).innerHTML = this.count--;
setTimeout(this.countDown.bind(this),1000);
}
}
</script>
</body>
</html>
好绕,没怎么明白this的用法!!!