call 的实现原理
call 的实现原理
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>
<script>
Function.prototype.calls = function (context) {
if (typeof this !== 'function') {
console.log('error type this');
}
let args = [...arguments].slice(1);
result = null;
context = context || window;
context.fn = this;
result = context.fn(...args);
delete context.fn;
return result;
}
let dog = {
a: 12,
eatFish: function (param, param2) {
console.log(`this:`, this, `第一个参数${param},第二参数${param2}`)
}
}
let cat = {
name: 'cat'
}
dog.eatFish.calls(cat, '鲤鱼', '鲈鱼');
</script>
</head>
<body>
</body>
</html>