用于从对象范围内访问对象属性的JavaScript语法



我有这个函数:

function Entity(textureSrc)
{
    var entity = {
        texture: textureSrc,
        position: { x: 0, y: 0 },
        test: this.texture,
        construct: function()
        {
            alert(this.test);
        }
    }
    return entity;
}

然后这个测试代码:

var testObject = Entity("Textures/AirTexture.png");
testObject.construct();

作为测试,我试图在为entity创建新属性时使用entity.texture的值——我不太清楚这样做的语法是什么

我试过:

  • test: this.texture
  • test: entity.texture
  • test: texture

但这些都不起作用;它们都产生CCD_ 6。

此外,在construct方法中使用单词this是否正确用于访问test,或者应该采取不同的做法?

在"test"行中,"this"还不存在(因为您正在定义它)。

然而,在构造函数中使用它是有效的,因为this将在计算该函数时存在(并且将指向您期望的内容,除非您重新绑定该函数)。

正如Corbin所说-读一读Johns的一篇旧帖子可能仍然是个好主意简单的"类"实例化

应该指出一个简单快速的对象创建方法:

function Entity(textureSrc) {
    if ( !(this.instanceof Entity) ) {
        return new Entity(textureSrc)
    }
    this.texture = textureSrc,
    this.position = {
        x: 0,
        y: 0
    }
}
Entity.prototype = {
    construct: function () {
        alert(this.texture)
    }
}

这样你就可以用你描述的相同方式进行实体化:

var testObject = Entity("Textures/AirTexture.png");
testObject.construct();

最新更新