2013-03-21 84 views
3

我具有以下的javascript不能在另一個函數訪問變量內部對象常量

var Obj = { 
    init: function() { 
     this.over = $('<div />').addClass('over'); 
     $('body').append(this.over); 
     $('.click').on('click', this.show); 
    }, 
    show: function() { 
     console.log(this.over); 
    } 
} 

Obj.init(); 

當這樣做是當用戶點擊一個鏈接.click然後它觸發show功能和註銷中創建的DOM元素代碼init功能。 但問題是,它然後註銷未定義。爲什麼?如何解決它?

回答

4

試試這個:

var Obj = { 
init: function() { 
    this.over = $('<div />').addClass('over'); 
    $('body').append(this.over); 
    $('.click').on('click', this.show); 
}, 

show: function() { 
    // here the 'this' is the button , not the obj object .. 
    console.log($('.over')); 
} 
} 

Obj.init(); 

另一種選擇:

var Obj = { 
init: function() { 
    this.over = $('<div />').addClass('over'); 
    $('body').append(this.over); 
    var that = this; 
    $('.click').on('click', function(e){ 
     that.show.call(that, e); // calling the show function with call, causing 'this' to be obj 
    }); 
}, 

// 'this' is the obj 
show: function (e) { 
    console.log(this.over); 
} 
} 

Obj.init(); 
+0

希望它有幫助,並解決您的問題,如果您需要幫助瞭解某事,請告訴我。 – IdanHen 2013-03-21 07:31:16

+0

謝謝你的幫助。還有一件事你可以看看這個http://jsfiddle.net/SQGsZ/1/。爲什麼我沒有註銷? – 2619 2013-03-21 07:48:01

+1

Obj.me; => Obj.me(); //在第9行! – IdanHen 2013-03-21 07:50:51

2

這裏的問題是,thisObj)的範圍。

使用下面的代碼來解決您的問題。

var Obj = { 
init: function() { 
    this.over = $('<div />').addClass('over'); 
    $('body').append(this.over); 
    $('.click').on('click', $.proxy(this.show, this)); 
}, 

show: function() { 
    console.log(this.over); 
} 
}; 

Obj.init(); 

瞭解jQuery.proxy

+0

上下文,而不是範圍。 – Quentin 2013-03-21 07:36:48

0

存儲在this.showon功能。當它被調用時,它不會在Obj的上下文中調用,所以this不是Obj

您需要創建一個不依賴於在Obj環境中調用的新函數。

要做到這一點,最簡單的方法是使用bind

$('.click').on('click', this.show.bind(this)); 

但是,這limited browser support

您也可以使用閉包:

var myObj = this; 
var show = function() { 
    myObj.show() 
} 
$('.click').on('click', show); 
0

當一個函數結合使用jQuery的事件,在這個函數被調用的背景是,已被點擊的DOM對象。

var Obj = { 
init: function() { 
    this.over = $('<div />').addClass('over'); 
    $('body').append(this.over); 
    var that = this; 
    $('.click').on('click', function(){ 
     // console.log(this) will log the dom object 
     that.show.call(that) 
    }); 
}, 

show: function() { 
    console.log(this.over); 
} 
} 

Obj.init(); 
1

因爲jQuery注入了與'Obj'對象相對的'this'被點擊的DOM元素。一種解決方案是關閉:

var Obj = { 
    init: function() { 
    this.over = $('<div />').addClass('over'); 
    $('body').append(this.over); 
    $('.click').on('click', this.show()); 
    }, 

    show: function() { 
    var self = this; 
    return function() { 
     console.log("over:", self.over); 
    } 
    } 
} 
Obj.init(); 
相關問題