call、apply模拟实现

模拟思路

  1. 将当前函数设置为 call、apply 对象的属性
  2. 执行该属性
  3. 删除该属性
  4. 返回值

call() 模拟实现

es5实现

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
//简单模拟Symbol属性
function mySymbol(obj) {
var unique_proper = "00" + Math.random();
if (obj.hasOwnProperty(unique_proper)) {
arguments.callee(obj)//如果obj已经有了这个属性,递归调用,直到没有这个属性
} else {
return unique_proper;
}
}

Function.prototype.myCall = function (context) {
var context = context ? Object(context) : window;
var fn = mySymbol(context);
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;
}

es6 实现

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
35
36
37
38
39
40
41
Function.prototype.myCall = function (context, ...args) {
if ( typeof this !== 'function') {
throw new Error(`${this}.call is not a function`)
}
// 获取调用`call2`的函数本身,用this获取,如果context不存在,则为window
context = context ? Object(context) : window;
let fn = Symbol(); // 保证fn函数的唯一性
context[fn] = this;

let result = context[fn](...args) //把参数传给context.fn执行返回

// delete context.fn
delete context[fn]
return result;
}

// 测试一下
var value = 2;

var obj = {
value: 1
}

function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}

bar.myCall(null); // 2

console.log(bar.myCall(obj, 'kevin', 18));
// 1
// Object {
// value: 1,
// name: 'kevin',
// age: 18
// }

apply() 模拟实现

es5实现

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
//简单模拟Symbol属性
function mySymbol(obj) {
var unique_proper = "00" + Math.random();
if (obj.hasOwnProperty(unique_proper)) {
arguments.callee(obj)//如果obj已经有了这个属性,递归调用,直到没有这个属性
} else {
return unique_proper;
}
}

Function.prototype.myApply = function (context, arr) {
var context = context ? Object(context) : window;
var fn = mySymbol(context);
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;
}

es6实现

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
35
36
37
38
39
40
41
42
43
44
45
Function.prototype.myApply=function(context, args){
if ( typeof this !== 'function') {
throw new Error(`${this}.apply is not a function`)
}
// 获取调用`myApply`的函数本身,用this获取,如果context不存在,则为window
context = context ? Object(context) : window;
let fn = Symbol(); // 保证fn函数的唯一性
context[fn] = this;

let arr = args ? args : [];
let result = context[fn](...arr);
// 从上下文中删除函数引用
delete context.fn;
return result;
}

// 测试
var obj ={
name: "xb",
getName: function(age){
console.log(this.name + ":" + age);
}
}

var obj2 ={
name: "xb",
getName: function(age){
return {
value: this.name,
age: age
}
}
}

var name = "window.name";

var me = {
name: "axuebin"
}

obj.getName(25); // xb:25
obj.getName.myApply(); // window.name:undefined
obj.getName.myApply(null, [25]); // window.name:25
obj.getName.myApply(me, [25]); // axuebin:25
obj2.getName.myApply(me, [25]); // {value: "axuebin", age: 25}

用apply() 实现 call()

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
Function.prototype.callOne = function(context) {
return this.myApply(([].shift.myApply(arguments)), arguments)
//巧妙地运用上面已经实现的applyFive函数
}

// 测试一下
var value = 2;

var obj = {
value: 1
}

function bar(name, age) {
console.log(this.value);
return {
value: this.value,
name: name,
age: age
}
}

bar.callOne(null); // 2

console.log(bar.callOne(obj, 'kevin', 18));
// 1
// Object {
// value: 1,
// name: 'kevin',
// age: 18
// }

bind() 模拟实现

  1. 修改this指向
  2. 动态传递参数
  3. 兼容new关键字

一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。

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
var value = 2;

var foo = {
value: 1
};

function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}

bar.prototype.friend = 'kevin';

var bindFoo = bar.bind(foo, 'daisy');

var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin

注意:尽管在全局和 foo 中都声明了 value 值,最后依然返回了 undefind,说明绑定的 this 失效了,如果大家了解 new 的模拟实现,就会知道这个时候的 this 已经指向了 obj。

es5实现

JavaScript深入之bind的模拟实现

手写bind

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Function.prototype.myBind = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}

var self = this;
var args = [].slice.call(arguments, 1);

var fNOP = function () {};
var fBound = function () {
var bindArgs = [].slice.call(arguments);
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
}
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}

// 举个例子
var foo1 = {
value: 1
};
function bar1(name, age) {
console.log(this.value);
console.log(name);
console.log(age);
}
var bindFoo1 = bar1.myBind(foo1, 'daisy');
bindFoo1('18');
// 1 'daisy' '18'

// new 的例子
var value = 2;
var foo = {
value: 1
};
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.myBind(foo, 'daisy');
var obj = new bindFoo('18');
// undefined
// daisy
// 18
console.log(obj.habit);
console.log(obj.friend);
// shopping
// kevin

es6实现

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
Function.prototype.myBind = function(context) {
//先判断调用函数的对象是否为function,不是就跑出错误。
if ( typeof this !== 'function') {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable")
throw new Error(`${this}.bind is not a function`)
}
const self = this
//获取传入的参数
const args = [...arguments].slice(1)
//先定义一个空函数进行中转
const fNOP = function () {}
const fBound = function() {
//获取函数执行的时候的参数
const bindArgs = [...arguments]
//判断调用的函数是否为构造函数,如果是构造函数this指向实例,将this绑定到实例
//如果函数不是构造函数,将this指向context
return self.apply( this instanceof fNOP? this : context, [...args, ...bindArgs])
}

// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承绑定函数的原型中的值
fNOP.prototype = this.prototype
// 如果z执行上面的语句,就会造成直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype。这个时候,我们可以通过一个空函数来进行中转:
fBound.prototype = new fNOP()
return fBound
}

参考文章

JavaScript深入之call和apply的模拟实现

JavaScript基础心法——call apply bind

更高阶版本:面试官问:能否模拟实现JS的call和apply方法