开发者

Is it possible to make an object that acts like a function when called in Javascript?

开发者 https://www.devze.com 2023-03-22 16:06 出处:网络
I want to make an object that has properties but can also be called. Sort of like 开发者_JAVA技巧the toString property that returns a string that represents the object when it\'s used as a string.

I want to make an object that has properties but can also be called. Sort of like 开发者_JAVA技巧the toString property that returns a string that represents the object when it's used as a string.

something that works like this:

o = {
  prop: 2
  toFunction: function(a) {
    return a;
  }
}

o('foo'); // returns foo
o.prop; // returns 2


Function is an object in JavaScript so you can do:

var o = function(a) { return a; }
o.prop = 2;

and so

o('foo'); // returns foo
o.prop; // returns 2
0

精彩评论

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