开发者

Can the object you create with a constructor function ever itself be a function?

I hope this question makes sense. Can I ever do something like the following:

function constructor_function开发者_开发知识库() {...code...};

var a = new constructor_function();

a();


If a constructor returns an object, that will be the value of the new .. expression. A function is an object, so you do what you want:

function ConstructorFunction() {
    return function () { alert("A function!"); };
}

var a = new ConstructorFunction();

a();


function Wrapper(constr, func) {
    return function() {
        var f = func();
        constr.apply(f, arguments);
        return f;
    }
}

function ConstructorFunction() {
    return function() {
        console.log("A function");
    }
}

function Constructor() {
    this.foo = 42;
}

var MyFunction = Wrapper(Constructor, ConstructorFunction);
var o = MyFunction();
o(); // A function
console.log(o.foo); // 42

To both manipulate the this state as intended and have the object returned be a function is difficult to do without a lot of extra hoops to jump through.

This is about as easy I could make it. You have your standard Constructor function that manipulates this as an object. Then you have your ConstructorFunction which is the function you want the constructor to return. This must be a factor that returns a new function each time it's called.

You wrap the two together to get a function which returns an object which both has the returned function and the manipulation of state.

Live example


You can return a function from the constructor, but then it's not really a constructor. You can just use the function as a regular function, the new keyword is not needed:

function constructor_function() {
  return function() { alert(42); }
};

var a = constructor_function();

a();

As a function is an object, you can even add properties to it:

function constructor_function() {
  var t = function() { alert(42); }
  t.size = 1337;
  return t;
};

var a = constructor_function();

a();
alert(a.size);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜