[1] JavaScriptの「this」は「4種類」??
[2] jQuery入門 > thisについて
1:メソッド呼び出しパターン[1]
- var myObject = {
- value: 10,
- show: function() {
- alert(this.value); // 10 (thisはmyObject)
- }
- }
- myObject.show();
thisはmyObject。
2:関数呼び出しパターン[1]
- var myObject = {
- value: 10,
- show: function() {
- alert(this.value); // 10 (thisはmyObject)
- show_this();
- function show_this() {
- alert(this.value); // undefined (thisはグローバルオブジェクト)
- }
- var self = this; // myObjectを使いたい場合はthisをselfに退避する
- show_self();
- function show_self() {
- alert(self.value); // 10 (selfはmyObject)
- }
- }
- };
- myObject.show();
thisはグローバルオブジェクト
myObjectを使いたい場合はthisをselfに退避する
myObjectを使いたい場合はthisをselfに退避する
3:コンストラクタ呼び出しパターン[1]
- var MyObject = function(value){
- this.value = value;
- this.show = function() {
- alert(this.value); // 10 (thisは生成されたインスタンスmyObject)
- };
- }
- var myObject = new MyObject(10);
- myObject.show();
thisは生成されたインスタンスmyObject
4:apply,call呼び出しパターン[1]
省略
5:jquery呼び出しパターン[2]
- var MyObject = function(value){
- this.value = value;
- this.show = function() {
- alert(this.value); // 10 (thisは生成されたインスタンスmyObject)
- };
- var self = this; // myObjectを使いたい場合はthisをselfに退避する
- $("#target").click(function(){
- alert(this.id); // target (thisはイベントが発生したDOM要素)
- alert($(this).text()); // click me (DOM要素をjQueryオブジェクトに変換している)
- alert(this.value); // undefined (thisはイベントが発生したDOM要素)
- alert(self.value); // 10 (selfはmyObject)
- });
- }
- var myObject = new MyObject(10);
jqueryでは、
イベントで設定したfunction内で、thisはイベントが発生したDOM要素を指す。
元のthisを保持するために、var self = this; で退避する。