This is my second article about getting started


This binding priority

In the last article, we introduced four rules for the this binding. In development, we just need to find which rules apply to function calls. But if more than one rule is applied to a function call location, which rule takes precedence?

The default rule has the lowest priority

The default rule has the lowest precedence, because when there are other rules, this is bound by other rules

Explicit binding takes precedence over implicit binding

When both implicit and explicit binding exist, the final this refers to the value passed in by the explicit binding, saying that the explicit binding takes precedence over the implicit binding

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

var obj1 = {
  name: "zhangsan".foo: foo,
};

var obj2 = {
  name: "lisi".foo: foo,
};

// Implicit binding
obj1.foo(); // obj1 {name: "zhangsan", foo: ƒ}
obj2.foo(); // obj2 {name: "lisi", foo: ƒ}

Implicit binding and explicit binding exist together
obj1.foo.call(obj2); // obj2 {name: "lisi", foo: ƒ}
Copy the code

New binding is superior to implicit binding

When both the new binding and the implicit binding exist, the resulting this refers to the object created by the new, so the new binding takes precedence over the implicit binding

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

var obj = {
  name: "zhangsan".foo: foo,
};

new obj.foo();  // foo {}
Copy the code

The new binding is higher than the bind binding

  • The new binding cannot be used with call and apply, so there is no higher priority
function foo() {
  console.log(this);
}

var obj = {
  name: "zhangsan".foo: foo,
};

var obj2 = new obj.foo.call(obj); // Uncaught TypeError: obj.foo.call is not a constructor
Copy the code
  • The new binding can be used with bind, but ultimatelythisPointing to a newly created object, the new binding takes precedence over the bind binding
function foo() {
  console.log(this);
}

var obj = {
  name: "zhangsan".foo: foo,
};

var bar = foo.bind(obj);

new bar(); // foo {}
Copy the code

Binding priority

New Binding > Explicit Binding > Implicit Binding > Default binding