var name = "张三"
function show(){
console.log(this.name)
}
/* 函数正常调用的时候this指向window */
function go(){
var name = "李四"
show();
}
window.go();
/* 函数要有对象去调用,事件也是需要对象去执行的 */
1-1 call,applay
/* call 可以改变函数内部this关键字的指向 funName.call(obj) */
/* applay funName.applay(obj) */
var name = "王五";
var obj = {
name:"李四"
}
function go(){
console.log(this.name)
}
go();
go.call(obj);
go.apply(obj);
1-2 call和apply之间的区别
/*
应用场景:传递多个参数的情况
call 依次去传递
applay 需要传递数组
*/
var name = "window"
var zhang = {
name: "张三"
}
function show(a, b) {
console.log(this.name);
console.log(a + b)
}
// show(1,2)
// show.call(zhang,2,3);
show.apply(zhang,[1,2])
</script>
1-3 bind
/*
bind绑定的函数不会马上执行,只是改变了函数上下文的执行环境
call,applay调用的时候马上执行
*/
var name = "window"
var zhang = {
name: "张三"
}
var show = function(a,b){
console.log(this.name)
console.log(a+b);
}.bind(zhang);
show(2,3);
1-3-1 应用场景
<button id="btn">按钮</button>
<script>
var id = "1001"
var btn = document.getElementById("btn");
btn.onclick = function(){
setTimeout(function(){
console.log(this.id)
},1000)
}
</script>
# 定时器在事件中,还是window在调用的定时器,所以this指向window,输出"1001"
可以使用bind解决this关键字指向问题
<button id="btn">按钮</button>
<script>
var id = "1001"
var btn = document.getElementById("btn");
btn.onclick = function(){
setTimeout(function(){
console.log(this.id)
}.bind(btn),1000)
}
</script>
<button id="btn">按钮</button>
<script>
var id = "1001"
var btn = document.getElementById("btn");
btn.onclick = function(){
setTimeout(function(){
console.log(this.id)
}.bind(this),1000)
}
</script>
也可以使用箭头函数
btn.onclick = function(){
setTimeout(function(){
console.log(this.id)
}.bind(this),1000)
}