javascript中bind函數(shù)的作用實(shí)例介紹
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
button {background-color:#0f0;}
</style>
</head>
<body>
<button id="button"> 按鈕 </button>
<input type="text">
<script>
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // 彈出button
};
//可以看出上下文的this 為button
</script>
</body>
</html>
此時(shí)加入bind
var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // 彈出button
}.bind(text);
//可以看出上下文的this 為button
此時(shí)會(huì)發(fā)現(xiàn)this改變?yōu)閠ext
函數(shù)字面量里也適用,目的是保持上下指向(this)不變。
var obj = {
color: "#ccc",
element: document.getElementById('text'),
events: function() {
document.getElementById("button").addEventListener("click", function(e) {
console.log(this);
this.element.style.color = this.color;
}.bind(this))
return this;
},
init: function() {
this.events();
}
};
obj.init();
此時(shí)點(diǎn)擊按鈕text里的字會(huì)變色??梢?jiàn)this不為button而是obj。
bind()的方法在ie,6,7,8中不適用,需要擴(kuò)展通過(guò)擴(kuò)展Function prototype可以實(shí)現(xiàn)此方法。
if (!Function.prototype.bind) {
Function.prototype.bind = function(obj) {
var slice = [].slice, args = slice.call(arguments, 1), self = this, nop = function() {
}, bound = function() {
return self.apply(this instanceof nop ? this : (obj || {}),
args.concat(slice.call(arguments)));
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
此時(shí)可以看到ie6,7,8中也支持bind()。
slice = Array.prototype.slice,
或
array = Array.prototype.slice.call( array, 0 );
將類似數(shù)組轉(zhuǎn)換為數(shù)組
- javascript中的Function.prototye.bind
- javascript之bind使用介紹
- js apply/call/caller/callee/bind使用方法與區(qū)別分析
- js bind 函數(shù) 使用閉包保存執(zhí)行上下文
- JavaScript中的prototype.bind()方法介紹
- js設(shè)置組合快捷鍵/tabindex功能的方法
- javascript bind綁定函數(shù)代碼
- 淺談javascript中call()、apply()、bind()的用法
- JS中改變this指向的方法(call和apply、bind)
- 深入理解JS中的Function.prototype.bind()方法
相關(guān)文章
將form表單中的元素轉(zhuǎn)換成對(duì)象的方法適用表單提交
這篇文章主要介紹了如何將form表單中的元素轉(zhuǎn)換成對(duì)象,需要的朋友可以參考下2014-05-05
js根據(jù)屬性刪除對(duì)象數(shù)組里的相應(yīng)對(duì)象
這篇文章主要介紹了js根據(jù)屬性刪除對(duì)象數(shù)組里的相應(yīng)對(duì)象,需要的朋友可以參考下2023-07-07
基于純JS實(shí)現(xiàn)多張圖片的懶加載Lazy過(guò)程解析
這篇文章主要介紹了基于純JS實(shí)現(xiàn)多張圖片的懶加載Lazy過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
關(guān)于JS中的全等和不全等、等于和不等于問(wèn)題
等號(hào)和非等號(hào)的同類運(yùn)算符是全等號(hào)和非全等號(hào)。這兩個(gè)運(yùn)算符所做的與等號(hào)和非等號(hào)相同,只是它們?cè)跈z查相等性前,不執(zhí)行類型轉(zhuǎn)換。接下來(lái)通過(guò)本文給大家介紹JS中的全等和不全等、等于和不等于,一起看看吧2021-09-09
innerText和textContent對(duì)比及使用介紹
innerText使用過(guò)程中遇到了FireFox的兼容問(wèn)題FireFox不支持innerText方法但是有個(gè)類似的方法,叫textContent,類似innerText,都是用來(lái)獲取(設(shè)置)元素中text的方法,感興趣的朋友可以參考下2013-02-02

