【发布时间】:2012-11-29 20:11:52
【问题描述】:
你能告诉我为什么这行不通吗? (注意 this 关键字)
var post = {
url: 'http://myurl.com',
add: function() {
window.location = this.url + '/add';
},
edit: function() {
window.location = this.url + '/edit';
}
};
代码中的其他地方:
post.url = '<?php echo BASE_ADMIN . $postType ?>';
$(document).ready(function() {
$("#listing").aJqueryPlugin({
...
// Buttons and their callbacks
buttons : [
{name: 'Add', bclass: 'add', onpress : post.add},
{name: 'Edit', bclass: 'edit', onpress : post.edit},
],
...
});
线
post.url = ....
按预期运行。 post 中的 url 属性已更新。
但是,当我点击 Add 或 Edit 按钮并输入它们的功能时,this.url 是 undefined 因为 this 引用了按钮而不是 post 对象。为什么?那么我应该怎么做才能从回调中引用 url 属性?
【问题讨论】:
-
见“闭包”或
Function.bind。 -
这与闭包无关,而是执行上下文。
标签: javascript jquery class object reference