Reputation: 39456
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:
test: this.texture
test: entity.texture
test: texture
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
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
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