<script>
let obj = {
x: 100,
fn() {
console.log(this.x);
},
};
obj.fn();
function fn(a, b) {
console.log(this, a, b);
}
fn.call({ y: 200 }, 2, 3);
/**
* 手写函数call
*/
Function.prototype.myCall = function (context, ...args) {
if (context == null) {
context = globalThis;
}
if (typeof context !== "object") {
context = Object(context);
}
let key = Symbol();
context[key] = this;
let result = context[key](...args);
delete context[key];
return result;
};
// 测试代码
fn.myCall({ y: 200 }, 2, 3);
</script>