this关键字这是一个常用的关键字,它在函数作用域内自动生成,代表函数执行环境的上下文。如果开发时不知道this绑定到哪个对象,就容易出现bug。this绑定规则在独立使用函数时默认绑定,(不调用对象属性的引用)。this将默认绑定到全局对象或undefined.varlog=function(){console.log(this)}log()//window使用严格模式"usestrict";varlog=function(){console.log(this)}log()//undefined不可见绑定在函数被对象的属性引用时被调用。this会绑定在对象上。varobj={log:function(){console.log(this);}}obj.log()//obj显式绑定函数调用时,指定函数的this绑定对象。涉及的方法有call、apply和bind.varlog=function(){console.log(this)}vartarget={}varbindLog=log.bind(target)bindLog()//targetlog.call(target)//targetlog.apply(target)//target显式绑定比不可见绑定优先级高',log:log}hideObj.log.call(visibleObj)//visiblenew在实例化构造函数时绑定。构造函数的this会绑定到instance.functionconstruct(tag){this.tag=tag;}varinstance=newconstruct('instance')console.log(instance.tag)//instance
