views:

86

answers:

4

How would you implement a constructor together with named functions on an object in JavaScript?

This is how I'd like to use the object:

o("..."); // use the object's constructor

o.namedFunction("..."); // use a named member on the object

I don't want to have to "new up" object before it's usable... You could say I want the equivalent of a static class with a bunch of static methods and a constructor.

A: 

This SO question has several good suggestions and examples. Also, be certain to use new when you create an instance/object.

var obj = new MyClass();
obj.someMethod();
Upper Stage
A: 

I think that you want to have static members (in class-based OO languages) on your constructor functions.

In JavaScript functions are first-class objects, that means they can have properties and they can be handled just as any object:

functon Ctor (arg) {
  //...
}
Ctor.namedFunction = function () {
  // "static" member
};


var instance = new Ctor("..."); // use the object's constructor
Ctor.namedFunction("..."); // use a named member on the object

Notice that I added the namedFunction property directly to the Ctor function object.

CMS
A: 

This did the trick:

var o = function ()
{
    return "constructor";
};

o.namedFn = function ()
{
    return "namedFn";
};

console.log(o("test"));
console.log(o.namedFn("test"));
console.log(o("test"));
roosteronacid
A: 

Here's how I would do it, just to be able to share some properties inside my methods by using closures:

<html>
<head>
    <title>so</title>
</head>
<body>
    <script>
        function fn(arg){
            var init = arg;
            return {
                meth:function(arg){
                    alert(init + arg);
                }
            };
        };
        var obj = fn('Stack');
        obj.meth('Overflow');
    </script>
</body>
</html>

Something you don't have by declaring them externally.

Mic