具有继承属性的函数(可调用)对象

时间:2011-07-10 01:46:24

标签: javascript

有没有办法创建一个从另一个对象继承属性的函数/可调用对象?这可以使用__proto__,但该属性已弃用/非标准。是否有符合标准的方法来做到这一点?

/* 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

1 个答案:

答案 0 :(得分:1)

这是标准方式的doesn't seem to be possible

您确定不能只使用普通复制吗?

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

(如果我必须这样做,我也会隐藏idhello和类似的东西,而不是使用全局变量。