我正在尝试为调用、应用和绑定方法创建一个polyfill。
const user = {
firstName: "Christopher",
lastName: "Nolan",
};
const fullName = function (place, country) {
console.log(
`${this.firstName} ${this.lastName} is from ${place}, ${country}.`
);
};
//使用调用方法
fullName.call(user, "London", "UK");
//重新创建一个名为"的调用方法_呼叫";
Function.prototype._call = function (...args) {
const funcObj = this;
const params = args.slice(1);
return (function () {
const obj = args[0];
// How can I point out the obj to "this" keyword inside a funcObj without using the bind method as I mentioned below.
return funcObj.bind(obj, ...params)();
})();
};
fullName._call(user, "London", "UK");
是。只需使用
var myObject = this;
我理解你可能遇到的问题。有时,当您希望使用"this"对象时,"this"的上下文已经更改。有些人使用
var that = this;
以下是一些更深入的阅读内容。
https://dbwriteups.wordpress.com/2017/04/08/what-does-that-this-in-javascript-mean/
我不确定这是一个很好的实现,但您可以利用这样一个事实,即对于对象方法,作用域会自动设置为调用它的对象。
考虑到这一点,您可以使用范围作为原型创建一个对象,并将原始函数添加为方法,然后调用该方法。
const user = {
firstName: "Christopher",
lastName: "Nolan",
};
const fullName = function (place, country) {
console.log(
`${this.firstName} ${this.lastName} is from ${place}, ${country}.`
);
};
Function.prototype._call = function (scope, ...args) {
// symbol for the method name to avoid name collisions
const symbol = Symbol();
// create a new object from scope with the original function (this) as a method
const temp = Object.create(scope, {[symbol]: { value: this }});
// inside the method "this" will point to "temp" which is (effectively) "scope"
return temp[symbol](...args);
}
fullName._call(user, 'London', 'UK');