【问题标题】:Function (callable) objects with inherited properties具有继承属性的函数(可调用)对象
【发布时间】:2011-07-10 10:48:32
【问题描述】:

有没有办法创建一个从另一个对象继承属性的函数/可调用对象? __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

【问题讨论】:

标签: javascript


【解决方案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 和类似的东西,而不是使用全局变量)

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多