Arron Grier
Arron Grier

Reputation: 7

constructor not working properly

I have a simple object constructor that my testing function does not pass properly.

Here is the constructor:

function objCon(name,count) { //object constructor
    this.name = name;
    this.count = count;
}

Here is the testing function:

function testing() {
    var here = new objCon(n, 2);
    alert(here.name + ":" + here.count);
}

However, when I test it, I do not get any alert. I need to pass it to a larger function that will store objects in an array.

Upvotes: 0

Views: 83

Answers (3)

LexJacobs
LexJacobs

Reputation: 2533

The correct answer could be constructed from all the bits and pieces above, but the most important thing that you've missed is that you've only defined testing, you haven't actually invoked it.

In other words, the function testing now exists, but you haven't told it to run.

function objCon(name,count) { //object constructor
    this.name = name;
    this.count = count;
}

function testing() {
    var here = new objCon('n', 2); // modified to insert a string. n doesn't already refer to anything, but 'n' is a valid string that can be passed in as an argument.

    alert(here.name + ":" + here.count);
}

and now to invoke it:

testing();

and you will get your alert.

Upvotes: 0

RobG
RobG

Reputation: 147413

You should see a reference error in the console because:

    var here = new objCon(n, 2); // <-- n is not declared or otherwise initialised

So pass a suitable value for n, e.g.

    var here = new objCon('Fred', 2);

or maybe:

    var n = 'Fred';
    var here = new objCon(n, 2);

Also, the first letter of a constructor name is usually capitalised to show it's a constructor, so:

function ObjCon() {
  ...
}
...
    var here = new ObjCon('Fred', 2);
...

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107546

JavaScript is case-sensitive.

var here = new ObjCon(n, 2);
               ^

You've defined your function as objCon but used a capital O there instead.

Upvotes: 3

Related Questions