this指向

80 阅读1分钟

this的绑定方法一共有四种:

  • 默认绑定

  • 隐式绑定

  • 显示绑定

  • new绑定

一、默认绑定

例如:

function foo(){      
    console.log(this.a);
}
var a = 'test';
foo();

foo函数的this就默认绑定到了window对象上,在严格模式中,this为undefined。

二、隐式绑定

function foo(){
    console.log(this.name);
}
var obj ={
   name: 'test'
}
foo();

这个例子中的foo函数的this就被显式的绑定到了obj对象上。

1、隐式丢失

例如:

function foo(){
    console.log(this.name);
}

var obj ={
    name:'test',
    foo: foo
}

var bar = obj.foo;
bar();

此时bar的值是foo函数的引用,所以造成foo函数的this隐式丢失,指向了全局对象。

三、显示绑定

显示绑定就是使用call、apply函数进行绑定的。

区别:

apply的第二个参数为数组,而call的第二个参数为参数列表。

1、硬绑定

function foo() {
    console.log(this.name);
}
var obj ={
    name:'test"
}
function bar (){
   foo.call(obj);
}
bar(); // test

这种就是this的硬绑定,之后即使对bar函数使用call、apply,也无法改变它的this指向,它会一直指向obj。

2、软绑定

硬绑定的问题是一旦绑定了this,就无法再改变,而软绑定可以。

if (!Function.prototype.softBind){
    Function.prototype.softBind = fucntion (obj){
       var fn = this;
       var curried = [].slice.call(arguments, 1);
       var bound = function () {
           return fn.apply((!this || (this === window || global) ? obj : this), curried.concat.apply(curried, arguments));
       }
       bound.prototype = Object.create(fn.prototype);
       return bound;
    }
}

四、new绑定

使用new创建一个对象的过程:

  • 创建一个新的对象。

  • [[Prototype]]链接

  • 利用call方法让构造函数的this指向新对象。

  • 返回新对象。

五、优先级

  • new绑定
  • 显式绑定
  • 隐式绑定
  • 默认绑定