Don Viegues
Don Viegues

Reputation: 127

Using pointers to functions in javascript

Why is my code only working for object2?

function object1() {
    this.URL = "yahoo.com";
    this.getURL = function() { return this.URL; };
}

var object2 = new Object();
object2.URL = "gmail.com";
object2.getURL = function() { return this.URL; };

var sources = new Array();
sources[0] = object1;
sources[1] = object2;
i=0;

var source1 = sources[0];
console.log(source1.getURL());

var source2 = sources[1];
console.log(source2.getURL());

If I try to get the URL out of object1, I get this error: TypeError: source1.getURL is not a function

I am trying to handle multiple HTTP connection, which use different URLs and each one returns a different XML that I have to parse. I want to do this by creating an Array of objects and do a for each of them, get the URL and connect to it.

Upvotes: 0

Views: 155

Answers (2)

Igor Pavelek
Igor Pavelek

Reputation: 1444

Because object1 is a function, you have to create an instance of object1.

This will work

var sources = new Array();
sources[0] = new object1();
sources[1] = object2;

Upvotes: 0

Damp
Damp

Reputation: 3348

You need to do

var source1 = new sources[0]();

in order to instantiate a new object1.

Otherwise source1 points to the function object which has no such member as getURL

EDIT: You can also do sources[0] = new Object1(); but I assume this would not work well with the design you're going for (new Objects in array)

Upvotes: 5

Related Questions