call 实现的原理思路
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// call 实现的思路: 把需要执行的函数fn 和 需要改变的this指向obj 关联在一起
// let obj = {
// name:"Eric",
// age:29,
// fn:fn
// }
// function fn(x,y){
// console.log(this,x,y);
// return x + y
// }
// let result = fn.call(obj,10,20)
// console.log(result);
// Function.prototype.callOne = function(context,...params){
// // this ->fn 当前要执行的函数
// // context -> obj 需要改变的 this
// // params -> [10,20] 需要给函数 传递的实参信息
// context.xxx = fn;
// let result = context.xxx(...params);
// delete context.xxx;
// return result;
// }
// 优化1
Function.prototype.callOne = function(context,...params){
context == null ? context = window : null;
!/^(object|function)$/.test(typeof context) ? context = Object(context) : null;
// this ->fn 当前要执行的函数
// context -> obj 需要改变的 this
// params -> [10,20] 需要给函数 传递的实参信息
let key = Symbol('KEY')
context[key] = fn;
let result = context[key](...params);
delete context[key];
return result;
}
let obj = {
name:"Eric",
age:29
}
function fn(x,y){
console.log(this);
return x + y
}
let result = fn.callOne(100,20,20)
console.log(result);
</script>
</body>
</html>
我是Eric,手机号是13522679763

浙公网安备 33010602011771号