Skip to content

Instantly share code, notes, and snippets.

@cm3
Created January 16, 2014 13:37
Show Gist options
  • Save cm3/8455075 to your computer and use it in GitHub Desktop.
Save cm3/8455075 to your computer and use it in GitHub Desktop.
JavaScript 関数内の this が指すものは、関数をメソッドとして扱うか、コンストラクタとして扱うかで変化する ref: http://qiita.com/cm3/items/e8da2f8ffed64641bb07
var a = {"x" :function(){this.p = 1}};
console.log(a.p); // undefined
console.log(a.x.p); // undefined
//↑ここまでは共通
var x1 = a.x(); // x を a のメソッド扱いして実行、返り値を x1 に格納. 左辺を省いて a.x() だけでも下の結果は変化しない.
console.log(a.p); // 1. this は a を指していた.
console.log(x1.p); // TypeError. x1 が undefined なので.
console.log(a.x.p); // undefined. this は a.x を指しているわけではない.
var a = {"x" :function(){this.p = 1}};
console.log(a.p); // undefined
console.log(a.x.p); // undefined
//↑ここまでは共通
var x1 = new a.x(); // x をコンストラクタ扱いして新しいインスタンス x1 を生成. new が付いただけで左辺 x1 の意味合いが変わっていることに注意.
console.log(a.p); // undefined. this は a を指していない.
console.log(x1.p); // 1. this は x から生成されたインスタンス x1 を指していた.
console.log(a.x.p); // undefined. this は a.x を指しているわけではない.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment