【问题标题】:Javascript: reference variable in an array within same namespaceJavascript:同一命名空间内数组中的引用变量
【发布时间】:2016-07-26 16:25:04
【问题描述】:

我有以下命名空间,

var app = {
w: 200,
h: 200,
spacing: 5,
dataList:[
    // 1st column
    [1 * this.w, 1 * this.h, 0 * this.w, 0 * this.h, 'bedroom.jpg', 'Bedroom 1'],
    [1 * this.w, 1 * this.h, 0 * this.w, 1 * this.h, 'topFloorLounge.jpg', 'Top floor lounge'],
    [1 * this.w, 1 * this.h, 0 * this.w, 2 * this.h, 'garage.jpg', 'Garage'],
    // 2nd column
    [2 * this.w, 2 * this.h, 1 * this.w, 0 * this.h, 'livingRoom2.jpg', 'Living room 2'],
    [1 * this.w, 1 * this.h, 1 * this.w, 2 * this.h, 'gym.jpg', 'Gym']
]}

但是当我在控制台记录我的 dataList 时,dataList[0] 的结果是: 0: NaN 1: NaN 2: NaN 3: NaN 4: "bedroom.jpg" 5: "Bedroom 1"

显然,数组中的“this.w”不是指同一命名空间中的 w:200,我做错了什么?任何建议都非常感谢。

谢谢

【问题讨论】:

    标签: javascript arrays variables namespaces


    【解决方案1】:

    this.w 还不是属性,您需要 2 个步骤:

    var app = {
        w: 200,
        h: 200,
        spacing: 5,
        dataList:[]
    };
    
    app.dataList.push(
        // 1st column
        [1 * app.w, 1 * app.h, 0 * app.w, 0 * app.h, 'bedroom.jpg', 'Bedroom 1'],
        [1 * app.w, 1 * app.h, 0 * app.w, 1 * app.h, 'topFloorLounge.jpg', 'Top floor lounge'],
        [1 * app.w, 1 * app.h, 0 * app.w, 2 * app.h, 'garage.jpg', 'Garage'],
        // 2nd column
        [2 * app.w, 2 * app.h, 1 * app.w, 0 * app.h, 'livingRoom2.jpg', 'Living room 2'],
        [1 * app.w, 1 * app.h, 1 * app.w, 2 * app.h, 'gym.jpg', 'Gym']
    );
    

    【讨论】:

      【解决方案2】:

      您的代码在全局上下文中执行。这意味着this 将引用window 对象。如果你想this引用app对象,你需要在它自己的方法中执行代码。

      var app = {
        w: 200,
        h: 200,
        spacing: 5,
        dataList: function() {
          return [
            // 1st column
            [1 * this.w, 1 * this.h, 0 * this.w, 0 * this.h, 'bedroom.jpg', 'Bedroom 1'],
            [1 * this.w, 1 * this.h, 0 * this.w, 1 * this.h, 'topFloorLounge.jpg', 'Top floor lounge'],
            [1 * this.w, 1 * this.h, 0 * this.w, 2 * this.h, 'garage.jpg', 'Garage'],
            // 2nd column
            [2 * this.w, 2 * this.h, 1 * this.w, 0 * this.h, 'livingRoom2.jpg', 'Living room 2'],
            [1 * this.w, 1 * this.h, 1 * this.w, 2 * this.h, 'gym.jpg', 'Gym']
          ];
        }
      };
      app.dataList();

      【讨论】:

      • 谢谢,您的回答更符合我的需要,因为它更独立,更接近我的原意。
      猜你喜欢
      • 2014-07-05
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2013-08-17
      • 2015-07-03
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      相关资源
      最近更新 更多