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
Release: 2016-05-16 16:34:59
Original
1193 people have browsed it
<!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>
Copy after login

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();
Copy after login

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;
};
}
Copy after login

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
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template