简体   繁体   English

为什么返回未定义?

[英]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. 设置TTT.tHtWthis是指周围的上下文,而不是对象本身。 You can't set it to TTT.cH at the moment either, because it's not defined yet. 您目前也无法将其设置为TTT.cH ,因为尚未定义。 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. 编辑:正如Oriol在评论中指出的那样,您还需要对TTT.ctx进行此TTT.ctx ,因为尚未定义canvas

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 . 那是通过使用getters和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: 如果您不希望以后再重置TTT.tHTTT.tW ,可以将它们定义为吸气剂:

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. 在这里,它被定义为一个函数,所以this的确会在那里工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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