var name = "张三"function show(){console.log(this.name)}/* 函数正常调用的时候this指向window */function go(){var name = "李四"show();}window.go();//张三/* 函数要有对象去调用,事件也是需要对象去执行的 */
call、apply
call、apply 可以改变函数内部this关键字的指向
var name = "王五";var obj = {name:"李四"}function go(){console.log(this.name)}go();go.call(obj);go.apply(obj);
当需传多个参数时
call 依次去传递
applay 需要传递数组
var name = "window"var zhang = {name: "张三"}function show(a, b) {console.log(this.name);console.log(a + b)}show(1,2)//window//3show.call(zhang,2,3);//张三//5show.apply(zhang,[1,2])//张三//3
bind
var name = "window"var zhang = {name: "张三"}var show = function(a,b){console.log(this.name)console.log(a+b);}.bind(zhang);show(2,3);//张三//5
使用场景
<button id="btn">按钮</button>var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){// console.log(this.id)window.setTimeout(function(){console.log(this.id)},1000)}//点击btn输出1001,因为是window执行setTimeout方法,this指向window
<button id="btn">按钮</button>var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){setTimeout(function(){console.log(this.id)}.bind(btn),1000)}//点击输出btn
var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){var self = this;setTimeout(function(){console.log(this.id)}.bind(self),1000)}//点击输出btnvar id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){setTimeout(function(){console.log(this.id)}.bind(this),1000)}//点击输出btn
箭头函数
var id = "1001"var btn = document.getElementById("btn");btn.onclick = function(){setTimeout(()=>{console.log(this.id)},1000)}//点击输出btn
