国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

javascript中bind函數(shù)的作用實(shí)例介紹

2019-11-20 14:05:22
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
<!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

復(fù)制代碼 代碼如下:

 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()。

復(fù)制代碼 代碼如下:

slice = Array.prototype.slice,



array = Array.prototype.slice.call( array, 0 );

將類似數(shù)組轉(zhuǎn)換為數(shù)組

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 庆阳市| 德昌县| 岱山县| 洪江市| 平凉市| 四川省| 尤溪县| 屯昌县| 门源| 达州市| 枣强县| 巢湖市| 石城县| 宁都县| 九龙城区| 林周县| 十堰市| 滁州市| 元朗区| 乌拉特前旗| 广宗县| 平阳县| 汉寿县| 嫩江县| 荥阳市| 会东县| 社会| 图们市| 高唐县| 天门市| 茌平县| 峨山| 剑川县| 旬邑县| 当雄县| 虎林市| 古丈县| 县级市| 福贡县| 永州市| 安阳市|