pig's diary

何でも忘れるので万年初心者ね

クロージャ関数のthisは誰?

var f = fHandler();
f(); // yeah!

function fHandler () {
  var handlerSelf = this;
  return function () {
    if (handlerSelf === this) {
      console.log('yeah!');
    } else {
      console.log('ooh...');
    }
  }
}

うん

console.log("we're in " + this);
var f = fHandler();
f(); // yeah!

AnotherContext = function () {};
AnotherContext.prototype.f = function () {
  console.log("we're in " + this);
  var f2 = fHandler();
  f2(); // yeah!

  f(); // yeah!
};
AnotherContext.prototype.f();

function fHandler () {
  var handlerSelf = this;
  return function () {
    if (handlerSelf === this) {
      console.log('yeah!');
    } else {
      console.log('ooh...');
    }
  }
}

う〜ん・・・