在下面的代码中,当我从对象外部调用“some_function”时,它会发出零警报。 当我点击“some_button”时,也调用“some_function”,但在这种情况下它会发出未定义的警报。 有什么问题?
some_object = {
some_variable: 0,
some_button: $('<input />', {
type: "button",
value: "Click Me"
}),
some_function: function () {
alert(this.some_variable);
},
init: function () {
$("body").append(this.some_button);
this.some_button.click(this.some_function); // Result is undefined
}
}
some_object.init();
some_object.some_function(); // Result is 0
答案 0 :(得分:0)
some_function: function () {
alert(this.some_variable);
},
这指的是没有对象的按钮。 试试这个:
some_object = {
some_variable: 0,
some_button: $('<input />', {
type: "button",
value: "Click Me"
}),
some_function: function (variable) {
alert(variable);
},
init: function () {
$("body").append(this.some_button);
$this = this;
$this.some_button.click(function(){
$this.some_function($this.some_variable);
});
}
}
some_object.init();
some_object.some_function(some_object.some_variable);
答案 1 :(得分:0)
它发生了,因为当你注册一个点击处理程序时,它指的是一个按钮元素,而不是对象。相反,你可以打电话:
alert(some_object.some_variable);
答案 2 :(得分:0)
在此声明this.some_function中,'this'指的是单击按钮而不是对象'some_object'。
我认为你的陈述应该是这样的
this.some_button.click(some_object.some_function);
而不是
this.some_button.click(this.some_function); // Result is undefined
答案 3 :(得分:0)
将您的代码改为以下内容:
some_object = {
self = this,
some_variable: 0,
some_button: $('<input />', {
type: "button",
value: "Click Me"
}),
some_function: function () {
alert(self.some_variable);
},
init: function () {
$("body").append(self.some_button);
this.some_button.click(self.some_function); // Result is undefined
}
}
some_object.init();
some_object.some_function(); // Result is 0