gpt4 book ai didi

javascript - 如何使用ES6类扩展Function?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:39:45 25 4
gpt4 key购买 nike

ES6允许扩展特殊对象。因此可以从该函数继承。可以将此类对象称为函数,但是如何实现此类调用的逻辑呢?

class Smth extends Function {
constructor (x) {
// What should be done here
super();
}
}

(new Smth(256))() // to get 256 at this call?

任何类方法都通过 this引用类实例。但是,当将其作为函数调用时, this指的是 window。将类实例作为函数调用时,如何获得对它的引用?

PS: Same question in Russian.

最佳答案

super调用将调用Function构造函数,该构造函数需要一个代码字符串。如果要访问实例数据,则可以对其进行硬编码:

class Smth extends Function {
constructor(x) {
super("return "+JSON.stringify(x)+";");
}
}

但这并不令人满意。我们要使用闭包。

让返回的函数成为 can access your instance变量的闭包是可能的,但并不容易。好消息是,如果您不想调用 super,您仍然可以从ES6类构造函数中对任意对象进行 return。在这种情况下,我们会
class Smth extends Function {
constructor(x) {
// refer to `smth` instead of `this`
function smth() { return x; };
Object.setPrototypeOf(smth, Smth.prototype);
return smth;
}
}

但是我们可以做得更好,并且可以从 Smth中抽象出来:
class ExtensibleFunction extends Function {
constructor(f) {
return Object.setPrototypeOf(f, new.target.prototype);
}
}

class Smth extends ExtensibleFunction {
constructor(x) {
super(function() { return x; }); // closure
// console.log(this); // function() { return x; }
// console.log(this.prototype); // {constructor: …}
}
}
class Anth extends ExtensibleFunction {
constructor(x) {
super(() => { return this.x; }); // arrow function, no prototype object created
this.x = x;
}
}
class Evth extends ExtensibleFunction {
constructor(x) {
super(function f() { return f.x; }); // named function
this.x = x;
}
}

诚然,这在继承链中创建了一个额外的间接级别,但这并不一定是一件坏事(您可以扩展它而不是本地 Function)。如果要避免这种情况,请使用
function ExtensibleFunction(f) {
return Object.setPrototypeOf(f, new.target.prototype);
}
ExtensibleFunction.prototype = Function.prototype;

但请注意 Smth不会动态继承静态 Function属性。

关于javascript - 如何使用ES6类扩展Function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48564941/

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