...

View Full Version : 'this' is not actually this??



outofsight
12-13-2010, 11:20 AM
Hi,

Its been a long time since I did anything with js and it all escapes me now.

I have two objects from different script files.

For arguments sake...




function firstObject() {
this.internalId = 'firstObject';

this.addContent = function() {
alert(this.internalId);
}
return this;
}


function secondObject() {
this.internalId = 'secondObject';
return this;
}



Now, when I create instances of my two objects and call addContent on my first object...



var first = firstObject();
var second = secondObject();
first.addContent(second);


The alert I get for internalId is 'secondObject' when it should be 'firstObject'.

I am obviously missing something here, any advice?

Thanks in advance.

Kor
12-13-2010, 12:09 PM
I am obviously missing something here[...]

Yes. By short: to use a function as a constructor, you should call it using the token new


var first = new firstObject();
var second = new secondObject();


And so, there is no need to return the value (no need for return this within the constructor).

outofsight
12-13-2010, 12:18 PM
Yes. By short: to use a function as a constructor, you should call it using the token new


var first = new firstObject();
var second = new secondObject();


And so, there is no need to return the value (no need for return this within the constructor).

Doh, of course. You wouldn't believe the amount of hair pulled out over this and I knew it would come down to something simple.

Thanks very much :)

rnd me
12-13-2010, 06:43 PM
if you want to be lazy, coerce the Constructor:


function secondObject() {
if(this.RegExp==RegExp){return new arguments.callee }
this.internalId = 'secondObject';
return this;
}


you can cut and paste the red line in any constructor to guard against accidentally clobbering global variables.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum