Skip to content

Commit 19a40a5

Browse files
committed
feat: update CustomCall
1 parent b3e7361 commit 19a40a5

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

js/call.js

+14-11
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,25 @@
77

88
// fn.call(obj, ...arguments)
99

10-
Function.prototype.myCall = function (context) {
11-
context = context ? Object(context) : window;
12-
context.fn = this; // 重置上下文, 这里的this就是调用myCall的函数
13-
console.log(this);
14-
const args = [...arguments].slice(1); // 获取参数
15-
const result = context.fn(...args); // 执行函数
16-
delete context.fn; // 删除添加的过渡性函数,避免对象属性污染
17-
return result; // 返回结果
10+
Function.prototype.CustomCall = function (context, ...args) {
11+
context = context || window
12+
context.fn = this
13+
const ret = context.fn(...args) // fn执行时 内部的this指向context
14+
delete context.fn
15+
return ret
1816
}
1917

2018
// 浏览器环境下
21-
var a = 1, b = 2;
22-
var obj = { a: 10, b: 20 }
19+
const obj = { a: 10, b: 20 }
20+
21+
globalThis.a = 1
22+
globalThis.b = 2
23+
2324
function test(key1, key2) {
25+
// this 默认指向globalThis
26+
console.log(this)
2427
console.log(this[key1] + this[key2])
2528
}
2629
test('a', 'b') // 3
27-
test.myCall(obj, 'a', 'b') // 30
30+
test.CustomCall(obj, 'a', 'b') // 30
2831

0 commit comments

Comments
 (0)