开发者

Creating an object with a constructor and named members

开发者 https://www.devze.com 2022-12-17 19:45 出处:网络
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:

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 befor开发者_C百科e it's usable... You could say I want the equivalent of a static class with a bunch of static methods and a constructor.


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();


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.


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"));


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消