Edison
Edison

Reputation: 4291

Function does not get called

I am working on a following javascipt file

var utility = (function () {

    var i = 1;
    return {

        nameGen: function () {
            var name = "Number Of Candidate:" + i;
            i = i + 1;
            return name;
        }
    }


} ());

var name1 = utility.nameGen();
var name2 = utility.nameGen();
var name3 = utility.nameGen();

I am calling above javascript code from my html but it is not working?

Upvotes: 0

Views: 63

Answers (3)

Ramy Nasr
Ramy Nasr

Reputation: 2537

If you want to write OOP JS you should do something like:

function Utility() {
    this.candidates = 1;
    this.nameGen = function () {
        var name = 'number of candidates' + this.candidates;
        this.candidates++;
        return name;
    }
}

var utility = new Utility();
utility.nameGen(); // outputs "number of candidates1"
utility.nameGen(); // outputs "number of candidates2"
utility.nameGen(); // outputs "number of candidates3"

You can read more about OOP JS here.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

I ran it here (with Firefox 29 and Chrome 34.0.1847.131 and Internet Explorer 9), and added console.log() calls to output the result -

var utility = (function () {
    var i = 1;
    return {
        nameGen: function () {
            var name = "Number Of Candidate:" + i;
            i = i + 1;
            return name;
        }
    }
} ());

var name1 = utility.nameGen();
var name2 = utility.nameGen();
var name3 = utility.nameGen();
console.log(name1);
console.log(name2);
console.log(name3);

I got the output

Number Of Candidate:1
Number Of Candidate:2
Number Of Candidate:3

Upvotes: 2

gontrollez
gontrollez

Reputation: 6538

Close the function like this:

}) ();

Upvotes: 0

Related Questions