1、this
JavaScript中谁执行函数,this指向谁
setTimeout为window方法,this指向window
<button id="btn">btn</button><!-- this --><script>var id = 1001;var btn = document.getElementById("btn");btn.onclick=function(){console.log(this);console.log(this.id);setTimeout(function(){ //setTimeout为window方法,this指向windowconsole.log(this);console.log(this.id);},1000)}</script>
2、改变函数this指向问题
使用箭头替换function使this指向事件本身
<button id="btn">btn</button><!-- this --><script>/* 1、使用箭头可以解决this关键字指向问题 */var id = 1001;var btn = document.getElementById("btn");btn.onclick=function(){console.log(this);console.log(this.id);setTimeout(()=>{ //使用箭头替换function使this指向事件本身console.log(this);console.log(this.id);},1000)}</script>
3、普通函数this指向window
函数内部调用一个普通函数this指向window
<button id="btn">btn</button><!-- this --><script>var id = 1001;var btn = document.getElementById("btn");/* 函数内部调用一个普通函数this指向window */btn.onclick=function(){go();}function go(){console.log(this.id)}</script>
4、bind,call与apply方法
4-1.bind()
bind可以改变函数运行的上下文环境,bind函数中的参数传谁,this就指向谁
<!-- bind,call,apply --><script>var name = "window";var obj = {name:"obj",sayName:function(){console.log(this.name)}}/*1、事件中,谁执行事件指向谁2、对象的方法中,谁执行方法指向谁*/obj.sayName();/* bind可以改变函数运行的上下文环境,bind函数中的参数传谁,this就指向谁 */var show = function(){console.log(this.name);}.bind(obj)show();</script>

使用场景:
<button id="btn">btn</button><!-- this --><script>var id = 1001;var btn = document.getElementById("btn");btn.onclick=function(){setTimeout(function(){console.log(this.id);}.bind(btn),1000)}</script>

that写法:
<button id="btn">btn</button><!-- this --><script>var id = 1001;var btn = document.getElementById("btn");btn.onclick=function(){var that = this;setTimeout(function(){console.log(this.id);}.bind(that),1000)}</script>
4-2.call(),apply()方法
call(),apply()也可以改变函数内部this关键字的指向
1、call,apply是调用的时候执行
2、bind仅仅是改变了函数上下文的运行环境,不会马上执行
<!-- bind,call,apply --><script>var name = "window";var obj = {name:"obj",sayName:function(){console.log(this.name)}}function go(){console.log(this.name)}go();/* call也可以改变函数内部this关键字的指向go.call(changeThis)*/go.call(obj);go.apply(obj);/* bind,call,apply1、call,apply是调用的时候执行2、bind仅仅是改变了函数上下文的运行环境,不会马上执行*/</script>
4-3.call()和apply()的区别
函数存在多个参数的情况,call按顺序传参,apply必须传数组
<script>var name = "window";var obj = {name:"obj",}/* 函数存在多个参数的情况,call按顺序传参,apply必须传数组 */function go(a,b){console.log(this.name);console.log(a+b)}go(2,3)go.call(obj,2,3)go.apply(obj,[2,3])</script>

