Call Apply Bind can change the this direction of a function
The difference between call and apply
Different parameters
Call syntax
The function call (thisArg, arg1, arg2,...).Copy the code
Apply the grammar
func.apply(thisArg, [argsArray])
Copy the code
You can see that the first argument to call and Apply is the function’s this value at run time, that call receives a list of arguments, and that Apply receives the value of an array or array of classes
Application:
- Simple usage
Fn :function(){console.log(this.log)}} var person = {name:' x '} O.f n.c all (person) / / xiao MingCopy the code
- Adds an array to another array
var array = ['a', 'b'];
var elements = [0, 1, 2];
array.push.apply(array, elements);
console.info(array); // ["a", "b", 0, 1, 2]
Copy the code
- Determine the data type
let a = {}
Object.toString.prototype.call(a)
Copy the code
bind
grammar
function.bind(thisArg[, arg1[, arg2[, ...]]])
Copy the code
- ThisArg is passed to the target function as this
- Arg1, arg2 Arguments to the object function
- Returns a new function
usage
function LateBloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1; } / / declaration in 1 seconds bloom LateBloomer. Prototype. Bloom = function () {window. The setTimeout (this) declare) bind (this), 1000); }; LateBloomer.prototype.declare = function() { console.log('I am a beautiful flower with ' + this.petalCount + ' petals! '); }; var flower = new LateBloomer(); flower.bloom(); // After one second, call the 'declare' methodCopy the code
Call,apply and bind
Call and apply are called immediately, and bind is the function that returns the new one
Implement call by hand
Function.prototype.call2 = function (context) {
var context = context || window;
context.fn = this;
var args = [];
for(var i = 1, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + ']');
}
var result = eval('context.fn(' + args +')');
delete context.fn
return result;
}
Copy the code
es6
Function.prototype.call2 = function(context, ... reset) { var context = context || window; context.fn = this; var result = context.fn(... reset); delete context.fn return result; }Copy the code
To realize the apply
Function.prototype.apply = function (context, arr) { var context = Object(context) || window; context.fn = this; var result; if (! arr) { result = context.fn(); } else { var args = []; for (var i = 0, len = arr.length; i < len; i++) { args.push('arr[' + i + ']'); } result = eval('context.fn(' + args + ')') } delete context.fn return result; }Copy the code
To realize the bind
Function. Prototype. Bind2 = Function (context) {var self = this; var args = Array.prototype.slice.call(arguments, 1); var fNOP = function () {}; var fBound = function () { var bindArgs = Array.prototype.slice.call(arguments); return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs)); } fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }Copy the code
reference
Github.com/mqyqingfeng…