你能告訴我爲什麼這不起作用嗎? (注意這關鍵字)如何從同一對象的方法引用屬性?
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 = ....
按預期運行url property post已更新。
然而,當我點擊添加或編輯按鈕,和我輸入它們的功能,this.url是不確定因爲這引用按鈕,而不是後對象。爲什麼?我應該怎麼做才能從回調中引用屬性url?
請參閱「閉包」或「Function.bind」。 – 2012-11-29 20:13:06
這與閉包無關,但與執行上下文有關。 – Christoph
[Javascript:Object Literal引用自己的鍵的函數而不是'this']的可能的重複](http://stackoverflow.com/questions/10711064/javascript-object-literal-reference-in-own-keys-function-instead這個) – Bergi