call, apply and bind achieve

call, apply and bind achieve

To achieve call and apply
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

Function .prototype.call = function ( obj ) { the let context obj = || window ; // if context is null point window // To get the first call of the function call, this call point call function is executed context.fn = the this ; the let args = []; // to args [ "arguments [. 1]", "arguments [2]", "arguments [. 3]"] for ( the let I = . 1 ; I < arguments .length; I ++) { args .push ( "arguments [" + I + "]" ); } // the eval (string) calculate a string, and executes the JavaScript code // will automatically call the Array.toString herein args () this method










// we need to pass parameters to each context.fn () the let Result = the eval ( "context.fn (" + args + ")" ); Delete context.fn; return Result; };





Function.prototype.apply = function(obj, arr) {
let context = obj || window;
context.fn = this;
let result;
if (!arr) {
result = context.fn();
} else {
let args = [];
for (let i = 0, len = arr.length; i < len; i++) {
args.push("arr[" + i + "]");
}
result = eval("context.fn(" + args + ")");
}
delete context.fn;
return result;
};
Realization bind

before bind () method creates a new function, when a new function is called, bind () first argument as a sequence parameter after this it runs the argument will be passed as it passed parameters.
bind there is a feature that is a binding function can also create an object using the new operator: This behavior is like the original function as a constructor. This value provided is ignored while parameters are provided to simulate the function when calling. That time bind when the function returns as a constructor, specified when bind this value will fail, but the incoming parameters continue to apply.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function.prototype.bind = function(context) {
//调用 bind 的不是函数报错
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}

let self = this;
let args = Array.prototype.slice.call(arguments, 1);

let fNOP = function() {
};

let fBound = function() { The let bindArgs = the Array .prototype.slice.call ( arguments ); // when as a constructor, this refers to the example case the result is true, this refers to the binding function of this example, lets tied instance obtained from value for a given function // when used as an ordinary function, this point window, this time the result is false, this points to binding function of context return self.apply ( this instanceof FNOP? this : context, args.concat (bindArgs)) ; };






fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};

Original: big column  call, apply and bind achieve


Guess you like

Origin www.cnblogs.com/petewell/p/11606586.html