File tree 1 file changed +14
-11
lines changed
1 file changed +14
-11
lines changed Original file line number Diff line number Diff line change 7
7
8
8
// fn.call(obj, ...arguments)
9
9
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
18
16
}
19
17
20
18
// 浏览器环境下
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
+
23
24
function test ( key1 , key2 ) {
25
+ // this 默认指向globalThis
26
+ console . log ( this )
24
27
console . log ( this [ key1 ] + this [ key2 ] )
25
28
}
26
29
test ( 'a' , 'b' ) // 3
27
- test . myCall ( obj , 'a' , 'b' ) // 30
30
+ test . CustomCall ( obj , 'a' , 'b' ) // 30
28
31
You can’t perform that action at this time.
0 commit comments