javascript变量undefined(超出范围)

时间:2017-03-14 08:08:36

标签: javascript

我对引用变量有一个奇怪的问题。我的设置如下:

var pattern = {/* some object with patterns */};

var view = (new function() {

    this.create_single = function(response) {
        pattern.block // this returns pattern object correctly
    };

    this.create_multi = function(response) {
        pattern.multi_block // this returns pattern as undefined
    };

}());

var data = (new function() {

    this.acquisition = function(response) {
        view.create_single(response);
        view.create_multi(response);
    };

}());

所以在create_multi方法模式变量返回undefined,我没有任何线索为什么会发生这种情况。在Adobe Dreamweaver(我用来编写代码)中,我有一个行错误,上面写着'pattern' used out of scope。谁能帮我理解发生了什么?

感谢您的帮助;)

2 个答案:

答案 0 :(得分:1)

你的方法没问题,但你的“观察”方法没有任何回报。它适用于以下场景:

var pattern = {
    block: 1,
    multi_block: 2
};

var view = (new function() {

    this.create_single = function(response) {
        return pattern.block // this returns pattern object correctly
    };

    this.create_multi = function(response) {
        return pattern.multi_block // this returns pattern as undefined
    };


}());

答案 1 :(得分:0)

尝试没有参数传递

var pattern = {multi_block:"mblock", block:"block" };

var view = ( function() { 
   var create_single = function(response) {
      return pattern.block // this returns pattern object   correctly
   };
   
   var create_multi = function(response) {
    return  pattern.multi_block // this returns pattern as undefined
   };
   return create_single;
}());

console.log(view);