js學習進階中-bind()方法


有次面試遇到的,也是沒說清楚具體的作用,感覺自己現在還是沒有深刻的理解!

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的用法!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM