2016-04-06 5 views
1

Ich habe folgende Namespace,Javascript: Referenzgröße in einem Array innerhalb gleichen Namensraum

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

aber wenn ich meine Datalist-Konsole anmelden, ist das Ergebnis für die Datenliste [0] ist : 0: NaN 1: NaN 2: NaN 3: NaN 4: "bedroom.jpg" 5: "Bedroom 1"

offensichtlich, 'this.w' innerhalb des Arrays bezieht sich nicht auf w: 200 im selben Namensraum, was habe ich falsch gemacht? Irgendwelche Vorschläge werden sehr geschätzt.

Dank

Antwort

3

this.w noch nicht eine Eigenschaft ist, müssen Sie zwei Schritte:

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'] 
); 
+0

ich sehe. danke für die hilfe :-) –

1

Ihr Code in globalem Kontext ausgeführt wird. Dies bedeutet this bezieht sich auf window Objekt. Wenn Sie this Objekt app beziehen möchten, müssen Sie den Code innerhalb seiner eigenen Methoden ausführen.

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

+0

danke, deine antwort passt zu meinem bedarf mehr denn je ist es selbständiger und liegt näher an meinem ursprünglich vorgesehenen. –

Verwandte Themen