当前位置:Gxlcms > JavaScript > javascript中bind函数的作用实例介绍_javascript技巧

javascript中bind函数的作用实例介绍_javascript技巧

时间:2021-07-01 10:21:17 帮助过:6人阅读










此时加入bind

代码如下:

var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // 弹出button
}.bind(text);
//可以看出上下文的this 为button

此时会发现this改变为text

函数字面量里也适用,目的是保持上下指向(this)不变。

此时点击按钮text里的字会变色。可见this不为button而是obj。

bind()的方法在ie,6,7,8中不适用,需要扩展通过扩展Function prototype可以实现此方法。

此时可以看到ie6,7,8中也支持bind()。

代码如下:

slice = Array.prototype.slice,



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

将类似数组转换为数组

人气教程排行