2015-10-25

javascript:this

参考:
[1] JavaScriptの「this」は「4種類」??
[2] jQuery入門 > thisについて


1:メソッド呼び出しパターン[1]
  1. var myObject = {
  2. value: 10,
  3. show: function() {
  4. alert(this.value); // 10 (thisはmyObject)
  5. }
  6. }
  7. myObject.show();
thisはmyObject。


2:関数呼び出しパターン[1]
  1. var myObject = {
  2. value: 10,
  3. show: function() {
  4. alert(this.value); // 10 (thisはmyObject)
  5.  
  6. show_this();
  7. function show_this() {
  8. alert(this.value); // undefined (thisはグローバルオブジェクト)
  9. }
  10.  
  11. var self = this; // myObjectを使いたい場合はthisをselfに退避する
  12. show_self();
  13. function show_self() {
  14. alert(self.value); // 10 (selfはmyObject)
  15. }
  16. }
  17. };
  18. myObject.show();
thisはグローバルオブジェクト
myObjectを使いたい場合はthisをselfに退避する


3:コンストラクタ呼び出しパターン[1]
  1. var MyObject = function(value){
  2. this.value = value;
  3. this.show = function() {
  4. alert(this.value); // 10 (thisは生成されたインスタンスmyObject)
  5. };
  6. }
  7. var myObject = new MyObject(10);
  8. myObject.show();
thisは生成されたインスタンスmyObject

4:apply,call呼び出しパターン[1]

省略

5:jquery呼び出しパターン[2]
  1. var MyObject = function(value){
  2. this.value = value;
  3. this.show = function() {
  4. alert(this.value); // 10 (thisは生成されたインスタンスmyObject)
  5. };
  6. var self = this; // myObjectを使いたい場合はthisをselfに退避する
  7. $("#target").click(function(){
  8. alert(this.id); // target (thisはイベントが発生したDOM要素)
  9. alert($(this).text()); // click me (DOM要素をjQueryオブジェクトに変換している)
  10. alert(this.value); // undefined (thisはイベントが発生したDOM要素)
  11. alert(self.value); // 10 (selfはmyObject)
  12. });
  13. }
  14. var myObject = new MyObject(10);

jqueryでは、
イベントで設定したfunction内で、thisはイベントが発生したDOM要素を指す。
元のthisを保持するために、var self = this; で退避する。