0

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.

Alan Kis
  • 1,790
  • 4
  • 24
  • 47
  • 1
    [relevant](http://stackoverflow.com/questions/7694501/class-static-method-in-javascript/7694583#7694583). – zzzzBov Oct 15 '13 at 22:48
  • 1
    What do you mean by "*public member `id`*"? The `this.id` is a property of instances, so you cannot set that without creating an instance (unless you mean to set it on the prototype, where it would apply to all instances - including the not yet created ones) – Bergi Oct 15 '13 at 23:12
  • @Bergi I made a mistake. Yes, this.id is property of instance, but I also want to set some default value, and then increment it upon instantiation or calling method on class. – Alan Kis Oct 15 '13 at 23:18

1 Answers1

2

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;
    };
})();
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • What is `Foo` here? Looks like an object. – Madbreaks Oct 15 '13 at 22:47
  • But op says, "I want to call method id() on constructor without creating instance of Foo". I'm trying to wrap my head around the question, not doubting your answer. – Madbreaks Oct 15 '13 at 22:48
  • @Madbreaks: An instance of `Foo` is never created here… are you mixing up `Foo` and `Foo.prototype`, maybe? – Ry- Oct 15 '13 at 22:48
  • @Madbreaks: `Foo` is the object which represents the function bound to the name `Foo`. Basically the `function` block is the definition of `Foo`, but `Foo` is the object which represents the binding of that function. Calling `Foo` is executing the definiton of the `Foo` object. – user268396 Oct 15 '13 at 23:03
  • @AlanKis: Call `Foo.id()` in the constructor? – Ry- Oct 15 '13 at 23:04