this重定向
详细解析 Function.prototype.mybind
方法
定义与目的
- 定义: 这段代码是在
Function.prototype
上定义了一个名为mybind
的方法,目的是为了模拟 JavaScript 原生Function.prototype.bind
的功能。 - 目标: 允许你将一个函数绑定到特定的上下文 (
context
) 并预先设置一些参数,从而返回一个新的函数,这个新函数在被调用时会使用预设的上下文和参数。
工作流程
-
接收参数:
context
: 指定函数调用时的上下文对象。...args1
: 传递给新函数的预设参数列表。
-
处理逻辑:
- 上下文检查: 如果
context
是undefined
或null
,则将其默认设置为全局对象 (window
或global
,取决于环境)。 - 保存原始函数引用: 使用
_this
变量存储当前函数的引用,以备后续使用。
- 上下文检查: 如果
-
返回新函数:
- 新函数接收任意数量的参数 (
...args2
)。 - 在新函数内部:
- 将
_this
赋值给context.__fn
,创建一个临时属性用于调用原函数。 - 合并预设参数
args1
和新函数调用时传入的参数args2
。 - 执行
context.__fn
,即调用原函数,并传入合并后的参数列表。 - 删除
context.__fn
属性,避免污染context
对象。 - 返回原函数的执行结果。
- 将
- 新函数接收任意数量的参数 (
示例应用
假设有一个函数 sayHello(name)
,我们想要预先设置 name
参数,并且改变函数调用时的上下文。
Function.prototype.mybind = function(context, ...args1) {
context = (context === undefined || context === null) ? window : context
let _this = this
return function(...args2) {
context.__fn = _this
let result = context.__fn(...[...args1, ...args2])
delete context.__fn
return result
}
}
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
// 使用 mybind 方法
const greetJohn = sayHello.mybind(this, 'John');
greetJohn(); // 输出 "Hello, John!"
Function.prototype.myapply
方法详解
Function.prototype.myapply = function(context, args) {
context = (context === undefined || context === null) ? window : context
context.__fn = this
let result = context.__fn(...args)
delete context.__fn
return result
}
Function.prototype.mycall
方法详解
Function.prototype.mycall = function(context, ...args) {
context = (context === undefined || context === null) ? window : context
context.__fn = this
let result = context.__fn(...args)
delete context.__fn
return result
}