[英]can't access variable in another function inside object literal
我有以下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
function並注銷在init
函數中創建的dom元素。 但問題是它注銷未定義。 為什么? 怎么解決?
試試這個 :
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();
這里的問題是this
( Obj
)的范圍。
使用以下代碼解決您的問題。
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的更多信息
因為jQuery將點擊的DOM元素注入'this'而不是'Obj'對象。 一個解決方案是關閉:
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();
您將存儲在this.show
的函數this.show
給on
。 當它被調用時,它不會在Obj
的上下文中調用,所以this
不是Obj
。
您需要創建一個不依賴於在Obj
上下文中調用的新函數。
最簡單的方法是使用bind
:
$('.click').on('click', this.show.bind(this));
但這限制了瀏覽器的支持 。
你也可以使用一個閉包:
var myObj = this;
var show = function () {
myObj.show()
}
$('.click').on('click', show);
使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.