<!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>
function getInfo(age,vip) {
console.log('this1111',this);
return {
name:this.name,
age:age,
type:vip
}
}
var tina = {
name: 'tina'
}
// 不推荐
// tina.__proto__.getInfo = getInfo
// tina.getInfo = getInfo
console.log('getInfo.call()',getInfo.call(tina,18,"vip"));
// call()
// 1.任何函数都可以调用
// 2.他有n个参数,至少一个
// 3.第一个函数就是想要的改变的this指向,从第二个开始就是函数的参数
// 4.返回值是函数的返回值
// 手写call()
var newCall = function(obj){
// console.log(this) // 当前的this是需要去改变this的函数
// console.log(obj) // obj需要去指向this
// console.log('arguments',arguments);
obj = obj||window
var arr = []
for (let index = 1; index < arguments.length; index++) {
const element = arguments[index];
arr.push(element)
}
obj.fun = this
var res = obj.fun(...arr)
delete obj.fun
return res
// console.log('obj.fun()',obj.fun(18,"vip"));
}
Function.prototype.newCall = newCall
console.log('getInfo.newCall(tina,18,"vip");',getInfo.newCall(tina,18,"vip"));
console.log('tina',tina);
</script>
</body>
</html>
手写JavaScript中的call()方法
于 2022-07-04 23:47:29 首次发布