Home >Web Front-end >JS Tutorial >Introduction to the role of bind function in javascript_javascript skills

Introduction to the role of bind function in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:34:591222browse
<!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>

Join bind now

Copy code The code is as follows:

var text = document.getElementById("text");
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); // popup button
}.bind(text);
//You can see that this in the context is button

At this point you will find that this changes to text

This also applies to function literals, the purpose is to keep the up and down pointing (this) unchanged.

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

When you click the button, the text in the text will change color. It can be seen that this is not button but obj.

The bind() method is not applicable in IE, 6, 7, and 8. This method needs to be extended by extending the 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 &#63; this : (obj || {}),
args.concat(slice.call(arguments)));
};

nop.prototype = self.prototype;

bound.prototype = new nop();

return bound;
};
}

At this time, you can see that bind() is also supported in ie6, 7, and 8.

Copy code The code is as follows:

slice = Array.prototype.slice,

or

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

Convert array-like to array
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn