【问题标题】:odd value of "this" in javascriptjavascript中“this”的奇数值
【发布时间】:2013-08-20 15:18:54
【问题描述】:

在下面的代码中,根据 firebug,this 的值是 [function()],而不是定义返回的对象。


define(["dojo/dom", 
        "dojo/dom-construct", 
                ......., 
        "dojo/domReady!"], 

function(dom, 
         construct, 
         ........){ 

    return { 

        is_empty_attr: function(attr){ 
            if (attr.many){ 
                return attr.peeks.length === 0; 
            } else { 
                return !attr.peeks; 
            } 
        }, 
                ................ 

        add_button: function(attr){ 
            console.log(this); <- 1
            var self = this; 
            return new Button({ 
                label: 'add', 
                showLabel: false, 
                iconClass: "add_icon", 
                disabled: this.is_empty_attr(attr), <- 2
                onClick: function(){ 
                    if (attr.inline){ 
                        ajax.newObject(self.sub_path_func(attr), function(json){ 
                            self.object_table(json, "val_"+attr.path); 
                        }); 
                    } else { 
                        ajax.newObject(self.sub_path_func(attr), function(json){ 
                            self.object_dialog(json); 
                        }); 
                    } 
                } 
            }); 
        }, 

    };     
}); 

行 (

有谁知道为什么会发生这种情况以及如何解决它?

[edit] 我已经解决了这个问题(通过猜测),但在原始版本中,我将数组 [this.add_button, this.someotherbutton] 传递给另一个函数,该函数使用 attr 参数调用数组中的每个函数。所有方法都是 dojo 定义方法的相同返回对象的一部分。在我将 [this.add_button(attr), this.someotherbutton(attr)] (所以实际的按钮)作为第二个函数的参数传递之后,它就起作用了。

我仍然不明白这如何改变了 add_button 中的“this”值,因为调用 add_button 的两种方法似乎都具有可比性,所以如果有人能解释一下,我将不胜感激。[结束编辑]

干杯,拉斯

【问题讨论】:

  • 这将有助于查看调用 add_button 的示例,因为 JavaScript 中的 this 在方法调用时被绑定。
  • 我将编辑更多信息。

标签: javascript dojo this


【解决方案1】:

使用dojo/_base/declare 定义你的类:

define(["dojo/_base/declare",
        "dojo/dom", 
        "dojo/dom-construct", 
            ......., 
        "dojo/domReady!"], 

function(declare,
         dom, 
         construct, 
         ........){ 

    return declare([], {
        is_empty_attr: function(attr){ 
            ...
        },
        add_button: function(attr){
            ...
        }
    });
}); 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多