【问题标题】:How do I reference property from method of the same object?如何从同一对象的方法中引用属性?
【发布时间】: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 属性已更新。

但是,当我点击 AddEdit 按钮并输入它们的功能时,this.urlundefined 因为 this 引用了按钮而不是 post 对象。为什么?那么我应该怎么做才能从回调中引用 url 属性?

【问题讨论】:

标签: javascript jquery class object reference


【解决方案1】:

由于您使用的是 jQuery,您可以使用$.proxy

    {name: 'Add', bclass: 'add', onpress : $.proxy(post, "add")},
    {name: 'Edit', bclass: 'edit', onpress : $.proxy(post, "edit")},

这将返回一个新函数,该函数将调用由字符串命名的对象的方法。


它正在有效地做到这一点:

{name: 'Add', bclass: 'add', onpress : function() {
                                           return post["add"].apply(post, arguments);
                                       },
{name: 'Edit', bclass: 'edit', onpress : function() {
                                           return post["edit"].apply(post, arguments);
                                         },

由于函数中this 的值取决于函数的调用方式,因此您有时需要其他方法来确保获得正确的值。


你也可以在你的原始对象中设置这些,只要你知道你总是希望this 引用那个对象。

var post = {
    url: 'http://myurl.com'
};
post.add = $.proxy(function() {
    window.location = this.url + '/add';
}, post);
post.edit = $.proxy(function() {
    window.location = this.url + '/edit';
}, post);

这使用了$.proxy 的另一个签名,它允许您直接传递函数,后跟所需的this 值。

【讨论】:

  • 感谢您的回复!这在稍作调整后就可以工作,因为“添加”和“编辑”函数中的 this 现在引用了 Window。所以我不得不改变 this.url + "/add" 为 post.url + "/add"。
  • @LuisMartin: 使用$.proxy 后引用window?不应该。
  • 我无法理解为什么会在回调中发生这种情况。但是,在外部引用 this 有效:this.url = 'whatever';
  • @LuisMartin:this 的值取决于函数的调用方式。如果你做post.add()addthis的值将自动设置为post。但是如果你将post.add pass post.add 传递给另一个函数,你只是传递了方法,而不是对象,所以它忘记了它来自哪里。使用 $.proxy 返回一个新函数,该函数使用 post 对象调用 "add" 方法,以便保留其 this 值。
  • @user1689607:它确实在函数内部引用了 Window。事实上,为 post 更改 this 是可行的。
猜你喜欢
  • 2015-01-07
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 2011-03-11
相关资源
最近更新 更多