JS 手写 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>
Function.prototype.myCall = function (thisArg) {
if (thisArg === null || thisArg === undefined) {
thisArg = window;
}
if (typeof thisArg !== 'undefined' && typeof thisArg !== 'function' && typeof thisArg !== 'object') {
thisArg = Object(thisArg);
}
var argArr = Array.from(arguments).slice(1);
var uniqKey = Date.now().toString(36);
thisArg[uniqKey] = this;
eval("var re = thisArg[uniqKey](" + argArr.toString() + ")");
delete thisArg[uniqKey];
return re;
}
var obj = {
name: "laowang"
}
function fn(a, b, c) {
console.log(this, a + b + c);
}
var re = fn.myCall(obj, 1, 2, 3);
console.log(re)
</script>
</body>
</html>