简体   繁体   中英

Why does this return undefined?

var TTT = {
        canvas      : document.getElementById('canvas'),
        ctx         : canvas.getContext('2d'),
        cH          : 600,
        cW          : 600,
        // tile dimensions
        tH          : this.cH / 3,
        tW          : this.cW / 3
    };

// returns undefined... why? 
console.log(TTT.tH);

This got to be something very simple, but I can't seem to grasp why this is undefined...

When you set TTT.tH and tW , this refers to the surrounding context, not the object itself. You can't set it to TTT.cH at the moment either, because it's not defined yet. What you can do is set them after the object is initially defined.

var TTT = {
        canvas      : document.getElementById('canvas'),
        ctx         : canvas.getContext('2d'),
        cH          : 600,
        cW          : 600
    };

// tile dimensions
TTT.tH = TTT.cH / 3;
TTT.tW = TTT.cW / 3;

// returns undefined... why? 
console.log(TTT.tH);

EDIT: As pointed out in a comment by Oriol, you'll need to do this as well for TTT.ctx , as canvas isn't defined yet.

In addition to the answer i posted above , there's a second, completely different way of doing it. That's by using getters and setters .

If you don't care about being able to reset TTT.tH and TTT.tW at a later point, you can just define them as getters:

var TTT = {
        canvas      : document.getElementById('canvas'),
        ctx         : canvas.getContext('2d'),
        cH          : 600,
        cW          : 600,
        // tile dimensions
        get tH() { return this.cH / 3 },
        get tW() { return this.cW / 3 }
    };

// returns undefined... why? 
console.log(TTT.tH);

Here, it's defined as a function, and so this will indeed work there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM