繫結函式上下文

Version >= 5.1

每個函式都有一個 bind 方法,它將建立一個包裝函式,該函式將使用正確的上下文呼叫它。有關更多資訊,請參見此處

var monitor = {
  threshold: 5,
  check: function(value) {
    if (value > this.threshold) {
      this.display("Value is too high!");
    }
  },
  display(message) {
    alert(message);
  }
};

monitor.check(7); // The value of `this` is implied by the method call syntax.

var badCheck = monitor.check;
badCheck(15); // The value of `this` is window object and this.threshold is undefined, so value > this.threshold is false

var check = monitor.check.bind(monitor);
check(15); // This value of `this` was explicitly bound, the function works.

var check8 = monitor.check.bind(monitor, 8);
check8(); // We also bound the argument to `8` here. It can't be re-specified.

硬繫結

  • 硬繫結的物件是連結對 this 的引用。
  • 優點:當你想要保護特定物件不被丟失時,它非常有用。
  • 例:
function Person(){
    console.log("I'm " + this.name);
}

var person0 = {name: "Stackoverflow"}
var person1 = {name: "John"};
var person2 = {name: "Doe"};
var person3 = {name: "Ala Eddine JEBALI"};

var origin = Person;
Person = function(){
    origin.call(person0);
}

Person();
//outputs: I'm Stackoverflow

Person.call(person1);
//outputs: I'm Stackoverflow

Person.apply(person2);
//outputs: I'm Stackoverflow

Person.call(person3);
//outputs: I'm Stackoverflow
  • 因此,正如你在上面的示例中所述,無論你傳遞給 Person 的任何物件,它都將始終使用 person0 物件它是硬繫結的