function hello(name) {
// this:执行上下文,程序的运行环境
// this当前是window,全局
this.name = name;
// window.name=name
console.log(this);
}
// 输出:香蕉
hello("香蕉");
// bind(可以改变函数的this指向)
const obj = {
name,
};
// bind()只绑定不执行
let f = hello.bind(obj, "admin");
console.log(f());
// 输出:{name:admin}
// hello.bind(obj, "admin")();
// 如果函数中的this被重新绑定之后,要求立即执行
// 用call或apply
// hello.call(obj, "桃子");
// 输出:{name:桃子}
hello.apply(obj, ["西瓜", "哈密瓜"]);
// 输出:{name:西瓜}
// bind()案例
document.querySelector("button").addEventListener(
"click",
function () {
// this原来是绑定到按钮上的,bind()改变了this的指向
console.log(this.name);
// 猕猴桃
console.log(this);
//{name:猕猴桃}
}.bind({
name: "猕猴桃",
})
);
</script>
<!-- bind,call,apply:相同点,都可以改变this的指向
不同的点:
1.bind()只绑定,不执行
2.call,apply,绑定后立即执行,但参数不一样
3.call,参数是离散的一个一个传入
4.apply,参数以数组的形式统一传入 -->
<第三天学习>bind() call() apply()
最新推荐文章于 2024-09-14 18:52:56 发布
本文深入探讨JavaScript中this的概念,通过hello函数的示例展示了bind、call和apply如何改变函数的执行上下文。bind用于预设函数的this值而不立即执行,而call和apply则在设定this后立即执行。此外,还通过实例解释了bind在事件处理中的应用,以及call和apply在参数传递上的差异。
摘要由CSDN通过智能技术生成