definition:
bind()
Method creates a new function, in bind()
is called, this new function this
is specified as bind()
the first parameter, and the remaining arguments as parameters of the new function for use during calls.
usage:
bind()
The simplest use is to create a function, no matter how called, this function has the same this
value.
<script> var name='hhh'; function demo(){ console.log('demo.name',this.name); } var a={ name:"linjianbin", } var demo2= demo.bind(a); demo();///hhh demo2();//linjianbin </script>
2.bind()
Another simplest usage is to have a function preset initial parameters. As long as these parameters (if any) as a bind()
parameter written in this
the back. When the binding function is called, these parameters will be inserted into the starting position of the objective function parameter list, the parameters passed to the binding functions will follow them. ,
var demo= function(){ return arguments; } var demo2=demo.bind(demo,23); console.log(demo2(1,2,3,4,5));//23,1,2,3,4,5
3. By default, the use window.setTimeout()
, the this
key point to window
(or global
) objects. When the class method requires this
point to instances of the class, you may need to explicitly this
bind to the callback function, you do not lose the instance reference.
<script> function LateBloomer() { this.petalCount = 10 + 1; } // 在 1 秒钟后声明 bloom LateBloomer.prototype.bloom = function() { window.setTimeout(this.declare.bind(this), 1000); }; LateBloomer.prototype.declare = function() { console.log('I am a beautiful flower with ' + this.petalCount + ' petals!'); }; var Flower = new new LateBloomer (); flower.bloom (); // a second after call 'declare' Method </ script>