【问题标题】:Function-binding with super keyword in javascriptjavascript中使用super关键字的函数绑定
【发布时间】:2021-06-09 01:47:12
【问题描述】:

我想从绑定函数中调用“super”。

这是我的用例:我有许多来自不同父母的子班级。我想将相同的功能绑定到所有这些(而不是复制粘贴)。该函数需要调用同一函数的“超级”版本。

例子:

class Parent {
    func() {
        console.log("string1");
    }
}

function boundFunc() {
    super.func();
    console.log(this.string2);
}

class Child extends Parent {
    constructor() {
        super();
        this.string2 = "string2"
        this.func = boundFunc.bind(this);
    }
}

const child = new Child();
child.func();

我想得到结果:

string1 
string2

我得到了这个结果(不出所料,我愿意):

"SyntaxError: 'super' keyword unexpected here".

我尝试将超级函数作为参数传递给绑定。像这样:

function bindedFunc(thisArg, oriFunc) {
    oriFunc();
    console.log(this.string2);
}

class Child extends Parent {
    constructor() {
        super();
        this.string2 = "string2"
        this.func = bindedFunc.bind(this, super.func);
    }
}

结果(oriFunc 恰好未定义):

TypeError: oriFunc is not a function

有什么解决办法吗?谢谢

【问题讨论】:

  • 了解class 机制主要是一种在旧的基本机制之上构建对象结构的解析时“糖”功能,这一点很重要。在独立函数中使用super(就解析器而言)没有意义。

标签: javascript super function-binding


【解决方案1】:

除了super,您可以使用Object.getPrototypeOf 两次:一次从实例导航到其内部原型(即Child.prototype),一次从该实例导航到内部原型(Parent.prototype):

class Parent {
    func() {
        console.log("string1");
    }
}

function boundFunc() {
    Object.getPrototypeOf(Object.getPrototypeOf(this)).func();
    console.log(this.string2);
}

class Child extends Parent {
    constructor() {
        super();
        this.string2 = "string2"
        this.func = boundFunc.bind(this);
    }
}

const child = new Child();
child.func();

【讨论】:

  • 谢谢!但是我发现这并不完全等同于超级。这将无法从 Parent 访问任何属性。这将是:Object.getPrototypeOf(Object.getPrototypeOf(this)).func.call(this);。这也可以:Parent.prototype.func.call(this);。最后一个不太通用,但可能更漂亮,这取决于未来读者的用例:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 2011-02-11
  • 1970-01-01
相关资源
最近更新 更多