javascript中的bind

http://www.prototypejs.org/api/function/bind

In JavaScript, functions are executed in a specific context (often referred to as “scope”). Inside the function the this keyword becomes a reference to that scope. Since every function is in fact a property of some object—global functions are properties of the window object—the execution scope is the object from which the function was called, or (more precisely) the object that holds a reference to the function:


window.name = "the window object"

function scopeTest() {
  return this.name
}

// calling the function in global scope:
scopeTest()
// -> "the window object"

var foo = {
  name: "the foo object!",
  otherScopeTest: function() { return this.name }
}

foo.otherScopeTest()
// -> "the foo object!"

Because of the dynamic nature of the language, we can’t be sure that, for instance, otherScopeTest() will always be called on our foo object. The reference to it can be copied somewhere else, like on the window object:


// ... continuing from the last example

// note that we aren't calling the function, we're simply referencing it
window.test = foo.otherScopeTest
// now we are actually calling it:
test()
// -> "the window object"

The last call demonstrates how the same function can behave differently depending on its execution scope.

When you begin passing around function references in your code, you often want them to become fixated on a specific scope. Prototype can guarantee that your function will execute with the object you want under the this keyword just by invoking bind on it. You can also save the returned function and use it multiple times if you need so.

Examples
The code below is simply proof-of-concept:

var obj = {
  name: 'A nice demo',
  fx: function() {
    alert(this.name);
  }
};

window.name = 'I am such a beautiful window!';

function runFx(f) {
  f();
}

var fx2 = obj.fx.bind(obj);

runFx(obj.fx);
runFx(fx2);

你可能感兴趣的:(JavaScript)