不能在对象字面量内访问另一个函数中的变量
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
函数并注销在init
函数中创建的dom元素。但问题是它退出未定义。为什么?如何解决?
try this:
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
中的函数传递给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();
相关文章:
- 如何在JQuery函数中定义一个值,然后调用另一个函数并使用该值
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在另一个函数中使用变量this
- 在另一个函数成功结束后调用该函数
- 多次调用另一个javascript函数中的javascript函数
- 使用JS函数来使用另一个函数的语法?node.js
- 嵌套到另一个函数中的Fancybox函数;不起作用
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- javascript函数将数据添加到屏幕,但随后被另一个函数覆盖
- 另一个Ajax函数触发的Ajax函数不起作用
- 如何从另一个处理程序内部取消JavaScript事件处理程序函数的执行
- 如何在不预定义的情况下将javascript函数传递到另一个函数中
- 从另一个函数获得$this值
- 如何记录调用另一个函数的函数的返回值
- 它在另一个函数中嵌套后不会输出文本
- 如何将自动完成的值传递到另一个函数中
- 将一个函数作为参数传递给javascript中的另一个函数
- 同一事物的两个函数,一个崩溃,另一个不崩溃,为什么
- 从另一个函数延迟解析的返回
- 多次调用promise函数,直到另一个promise函数满足条件