<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button id="test">click me</button> </body> <script> function bind(context,name){ return function(){ return context[name].apply(context,arguments); //用apply函數改變函數的上下文,apply函數的第一個參數就是咱們須要的上下文對象。 } }; /*對比一下*/ //function bind(context){ //self = this; //保存this,即調用bind方法的目標函數 //return function(){ // return self.apply(context,arguments); //}; //}; var button = { clicked: false, click: function(){ this.clicked = true; console.assert(button.clicked,"The button has been clicked."); console.log(this); } }; var elem = document.getElementById("test"); elem.addEventListener("click",bind(button,"click"),false); //調用bind方法,bind方法的第一個參數就是咱們須要的上下文對象; //addEventListener()三個參數,分別是event,function,false </script> </html>
bind方法新增長 17/3/24html
<body> <button id="button" value="點擊"></button> <input type="text" id="text"> </body> <script> var button = document.getElementById("button"), text = document.getElementById("text"); button.onclick = function() { alert(this.id); // 彈出text }.bind(text); </script>
簡寫 fn.bind(this); app
用途:改變上下文的函數