0

In code:

function Foo() {
    this.someMethod = function() {
        console.log("property");
    };
}

Is possible to instantiate empty Foo object, and call someMethod on it? Like:

Foo.someMethod();

I got TypeError, which means not.

Ok, next, can I define default method like with __construct in PHP which execute some code upon instantiation of object, or even better let make evaluation of that function be some property value inside object, so even when I instantiate "empty" object, that function set some value upon instantiation of new object.

Alan Kis
  • 1,790
  • 4
  • 24
  • 47
  • 6
    `Foo` **is** the constructor, you should add the methods to the `prototype`, then simply create a new isntance with `new Foo().someMethod()` – elclanrs Oct 14 '13 at 22:01

1 Answers1

3

The way you are doing it,

var fooObj = new Foo(); 
fooObj.someMethod();

will work fine.


You can also try doing it this way:

var Foo = (function(){

    function Foo() {
        // Foo constructor
    }

    Foo.prototype.someMethod = function(){
        // public Foo function
    };

    var somePrivateFunction = function(){
        // private Foo function
    };

    return Foo;

})();

var fooObj = new Foo();
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 1
    I think you need a `return Foo` in there ... – Pointy Oct 14 '13 at 22:08
  • I __knew__ I was forgetting something @Pointy Thanks ^_^ – Naftali Oct 14 '13 at 22:09
  • I'm really confused now. Let's try this, can I call method on object constructor directly? Like `Foo.someMethod()` without creating new instance with new keyword? – Alan Kis Oct 15 '13 at 13:24
  • 1
    Not unless you do `Foo.someMethod = function(){ ... }` @AlanKis – Naftali Oct 15 '13 at 13:47
  • @Neal I get it now. In ^ case when i call method on class, do I instantiate new object which appears in global scope or just caling method on function, because constructor as it is, is only function? – Alan Kis Oct 15 '13 at 14:00