javascript中bind函数的作用实例介绍
作者:bea
<!DOCTYPE html><html><head><meta charset="utf-8"><style>button {background-color:#0f0;}</style></head><body><button id="button"> 按钮 </button><input type="text"><script&g
<!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>
此时加入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)不变。
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();
此时点击按钮text里的字会变色。可见this不为button而是obj。
bind()的方法在ie,6,7,8中不适用,需要扩展通过扩展Function prototype可以实现此方法。
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;
};
}
此时可以看到ie6,7,8中也支持bind()。
代码如下:
slice = Array.prototype.slice,
或
array = Array.prototype.slice.call( array, 0 );
将类似数组转换为数组
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- javascript学习笔记(一)基础知识
- js使用循环清空某个div中的input标签值
- javascript在当前窗口关闭前检测窗口是否关闭
- js+csss实现的一个带复选框的下拉框
- js监听鼠标事件控制textarea输入字符串的个数
- JavaScript声明变量时为什么要加var关键字
- Javascript基础知识(三)BOM,DOM总结
- Javascript基础知识(二)事件
- Javascript基础知识(一)核心基础语法与事件模型
- Javascript表单验证要注意的事项
- 使用phantomjs进行网页抓取的实现代码
- Javascript获取CSS伪元素属性的实现代码
- js获取元素相对窗口位置的实现代码
- Internet Explorer 11 浏览器介绍:别叫我IE
- 浏览器缩放检测的js代码
- 排序算法的javascript实现与讲解(99js手记)
- Javascript中封装window.open解决不兼容问题
- jQuery固定浮动侧边栏实现思路及代码
- js文件包含的几种方式介绍