Alan Kis
Alan Kis

Reputation: 1910

Method on class - static member

This is constructor:

function Foo() {
    this.id = 0;
}

I'm creating method on "class" here:

Foo.id = function() {
    return id form Product + 1; // pseudocode
}

Foo.id() // 1 
Foo.id() // 2

Well, I want to call method id() on constructor without creating instance of Foo, where id() method access to public member id and sets it to id + 1. Also, when I create instance, call id method upon creating it and sets id member. First thing are closures to me. Any help would be appreciated and links for further reading.

I'm going to create instances of Foo later, here is template:

var myFoo = new Foo({
    title: "titlevalue", // string
    price: n // ni is integer
});

I want that every instance also had id property, which is generated on instantiation, as there is default property id in constructor.

Upvotes: 0

Views: 101

Answers (1)

Ry-
Ry-

Reputation: 224857

A function is an object. Put a second property on your function.

Foo.currentId = 0;

Foo.id = function() {
    return ++Foo.currentId;
};

If you insist on making it “private”, you can create a function inside a function:

Foo.id = (function() {
    var id = 0;

    return function() {
        return ++id;
    };
})();

Upvotes: 2

Related Questions