1

I have the following namespace,

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']
]}

but when I console log my dataList, the result for the dataList[0] is: 0: NaN 1: NaN 2: NaN 3: NaN 4: "bedroom.jpg" 5: "Bedroom 1"

obviously, 'this.w' within the array is not referring to w:200 in the same namespace, what have I done wrong? any suggestions is much appreciated.

Thanks

2 Answers 2

3

this.w is not yet a property, you need 2 steps:

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']
);
Sign up to request clarification or add additional context in comments.

Comments

1

Your code is executed in global context. This means this will refer to window object. If you want this refer to app object, you need to execute the code within its own methods.

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();

1 Comment

thank you, your answer suits my need more as its more self contained and is closer to my originally intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.