gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:50:05 27 4
gpt4 key购买 nike

有什么方法可以创建一个从另一个对象继承属性的函数/可调用对象?这可以通过 __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

最佳答案

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 和类似的东西隐藏在闭包中,而不是使用全局变量)

关于javascript - 具有继承属性的函数(可调用)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6638654/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com