<!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 "codetitle">复制代码 代码如下:
slice = Array.prototype.slice,
或
array = Array.prototype.slice.call( array, 0 );
将类似数组转换为数组
最新资源
- 群星.2024-繁花电视剧原声带3CD【环球】【WAV+C
- 江希文.1994-伝说少女(饿狼伝说动画原声大碟)【
- 洪荣宏.2010-上爱的人【华特】【WAV+CUE】
- 《大牌国语情歌 经典再现 深情对唱 2CD》[WAV/分
- 《陈百强粉红色的一生精选 3CD》[FLAC/分轨][1.
- 《丁当 20首重量级歌曲 Fu Good 下一站天后 2CD
- 歌莉雅.2012-My.Voice.Story【环星】【FLAC分轨
- 群星.1993-一曲成名·青春无悔【飞碟】【WAV+CUE
- 刘德华.2000-爱无知(金装版)【NEWMELODY】【WAV
- 许巍《时光漫步》1CD[FLAC/分轨][804.3MB]