call
Function.prototype.call = function (context = window, ...args) {
if (typeof this != "function") {
throw new TypeError("Type Error");
};
// 避免在把函数赋值给 context 对象的时候,因为属性名冲突而覆盖掉原有属性
const fn = Symbol("fn");
context[fn] = this;
const res = context[fn](...args);
delete context[fn];
return res;
}
let obj = {
name: "Cindy"
};
function fn(age, hobby) {
console.log("name:" + this.name + " " + "age:" + age + " " + "hobby:" + hobby);
};
fn.call(obj, "18", "painting");
apply
Function.prototype.call = function (context = window, args) {
if (typeof this != "function") {
throw new TypeError("Type Error");
};
// 避免在把函数赋值给 context 对象的时候,因为属性名冲突而覆盖掉原有属性
const fn = Symbol("fn");
context[fn] = this;
const res = context[fn](...args);
delete context[fn];
return res;
}
let obj = {
name: "Cindy"
};
function fn(age, hobby) {
console.log("name:" + this.name + " " + "age:" + age + " " + "hobby:" + hobby);
};
fn.call(obj, ["18", "painting"]);
bind
Function.prototype.bind = function(context, ...args) {
if (typeof this !== "function") {
throw new Error("Type Error");
};
//保存 this 的值
var self = this;
return function F() {
return self.apply(context, [...args, ...arguments]);
}
}
let obj = {
name: "Cindy"
};
function fn(age, hobby) {
console.log("name:" + this.name + " " + "age:" + age + " " + "hobby:" + hobby);
};
newFn = fn.bind(obj, "18", "painting");
newFn();
网友评论