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

Function (callable) objects with inherited properties

本文关键字:调用 对象 函数 继承 属性      更新时间:2023-09-26

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

这在标准方式下似乎是不可能的。

你确定不能直接复制吗?

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

(如果我必须这样做,我也会隐藏id, hello和类似的东西在闭包内,而不是使用全局)