- 通过对象调用函数,this指向对象
- 直接调用函数,this指向全局对象
- 如果通过new调用函数,this指向新创建的对象
- 如果通过apply、call、bind调用函数,this指向指定的数据
- 如果是DOM事件函数,this指向事件源
**
bind():
bind(this指向,参数)
绑定this指向并且返回一个新函数,在bind()的里的参数会插入到执行函数的arguments的之前那参数的前面,但是bind的之后在new的话this指向将无效。绑定this指向之后假如之后多次调用this的指向都是绑定的this, call与apply 只是修改this指向,下次重新调用this指向就是原来的this指向,需要重新修改this指向
var x = 10 ;function show(){console.log(this.x)};show();var dyio={x:20,};var newshow = show.bind(dyio);console.log(new newshow().construtor); //此时this指向无效
bind的原理如下:
Function.prototype.newBind = function(target){// 谁调用newBind的this指向就是谁var self = this; // this指向是showvar arg = [].slice.call(arguments,1)//将传递给函数的参数的类数组对象从类数组第一位将其提取出来var temp =function(){};var f = function(){var _arg = [].slice.call(arguments,0) // 接受第二次参数//修改this指向,并且合并参数,会让第二次参数在其第一次参数的末尾添加return self.apply(this instanceof temp ? this : (target|| window),arg.concat(_arg));// return self.apply(target) 当 new 的时候 constructor会显示此对象的函数引用为 var f = function(){}}// 继承 防止new之后创建此对象的 Boolean 函数的引用为var f = function(){}temp.prototype = self.prototype;f.prototype = new temp();return f; // 形成闭包}function show (){console.log(this)}var duyio = {x:20,}var newSbow = show.newBind(duyio,1,2,3);newSbow(5); //第二次参数 会将第一次的参数插入第二次参数的前面console.log(new newSbow().constructor) // 此处的函数引用是 show()//constructor 属性返回对创建此对象的 Boolean 函数的引用
