0%

实现call()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

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 + ']');
}

// 这里 args 会自动调用 Array.toString() 这个方法。
var result = eval('context.fn(' + args + ')')

delete context.fn
return result;
}

ES6 写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Function.prototype.call3 = function (context) {
let target = context || window;
target.fn = this

let args = []
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i])
}

let result = target.fn(...args)

delete target.fn

return result
}
fn.call3(obj, '张三', '18')