3

Is there any way to create a function/callable object that inherits properties from another object? This is possible with __proto__ but that property is deprecated/non-standard. Is there a standards compliant way to do this?

/* A constructor for the object that will host the inheritable properties */
var CallablePrototype = function () {};
CallablePrototype.prototype = Function.prototype;

var callablePrototype = new CallablePrototype;

callablePrototype.hello = function () {
   console.log("hello world");
};

/* Our callable "object" */
var callableObject = function () {
   console.log("object called");
};

callableObject.__proto__ = callablePrototype;

callableObject(); // "object called"
callableObject.hello(); // "hello world"
callableObject.hasOwnProperty("hello") // false
Cristian Sanchez
  • 31,171
  • 11
  • 57
  • 63
  • possible duplicate of [How do I make a callable JS object with an arbitrary prototype?](http://stackoverflow.com/questions/548487/how-do-i-make-a-callable-js-object-with-an-arbitrary-prototype) – Christian C. Salvadó Jul 10 '11 at 04:22

1 Answers1

1

This doesn't seem to be possible in a standard way.

Are you sure you can't just use plain copying instead?

function hello(){
    console.log("Hello, I am ", this.x);
}

id = 0;
function make_f(){
     function f(){
          console.log("Object called");
     }
     f.x = id++;
     f.hello = hello;
     return f;
}

f = make_f(17);
f();
f.hello();

g = make_f(17);
g();
g.hello();

(If I had to do this I would also hide id, hello and similar stuff inside a closure instead of using globals)

Community
  • 1
  • 1
hugomg
  • 68,213
  • 24
  • 160
  • 246