Marty
Marty

Reputation: 39456

JavaScript syntax for accessing a property of an object from within the object scope

I have this function:

function Entity(textureSrc)
{
    var entity = {

        texture: textureSrc,
        position: { x: 0, y: 0 },
        test: this.texture,

        construct: function()
        {
            alert(this.test);
        }

    }

    return entity;
}

And then this test code:

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

As a test, I am trying to utilise the value of entity.texture when creating a new property for entity - I can't quite figure out what the syntax to do this would be.

I've tried:

But none of these work; they all result in undefined.

Also - is the use of the word this within the construct method correct for accessing test or should this be done differently?

Upvotes: 1

Views: 92

Answers (2)

martin
martin

Reputation: 2493

As Corbin stated - Probably still be a good idea to have a read of one of Johns old posts Simple "Class" Instantiation

Should point you towards a simple and fast method of object creation:

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)
    }
}

This way you can Entity in the same way you described:

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

Upvotes: 1

Corbin
Corbin

Reputation: 33437

On the "test" line, "this" doesn't exist yet (since you're in the middle of defining it).

It is, however, valid to use this in the construct function because this will exist when that function is evaluated (and will point to what you expect it to unless you rebind the function).

Upvotes: 3

Related Questions