An example of the bind function in javascript

  • 2020-03-30 04:00:36
  • OfStack

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
button {background-color:#0f0;}
</style>
</head>
<body>
<button id="button">  button  </button>
<input type="text">
<script>
var button = document.getElementById("button");
button.onclick = function() {
alert(this.id); //The pop-up button
};
//You can see that this in the context is button
</script>
</body>
</html>

Now I'm going to add bind


 var text = document.getElementById("text");
 var button = document.getElementById("button");
 button.onclick = function() {
 alert(this.id); //The pop-up button < br / >  }.bind(text);
 //You can see that this in the context is button

You'll notice that this has changed to text

This is also true in the literal of the function, which is to keep the upper and lower points of this constant.


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

Clicking on the button text changes the color. So this is not a button but an obj.

The bind() method does not work in ie,6,7,8, and needs to be extended to implement this method by extending 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;
};
}


slice = Array.prototype.slice,

or

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

Converts a similar array to an array


Related articles: