【问题标题】:ES6 Javascript Classes - define class method to an existing function [duplicate]ES6 Javascript Classes - 为现有函数定义类方法[重复]
【发布时间】:2016-01-08 06:48:33
【问题描述】:

在 es5 中,您可以通过将原型设置为现有函数来做到这一点,但是您将如何使用 ES6 类来实现这一点

//// ES5
function existingFn = function () {
    // does something
};

function MyClass () {
    // constructor stuff
};

MyClass.prototype.newFn = function () {
    // …
};

MyClass.prototype.existingFn = existingFn;

//// ES6
class MyClass {
    constructor() {}

    newFn() {
        // …
    }

    // ???????
    // existingFn = existingFn
    // ???????
}

【问题讨论】:

  • ES6 的类只是语法糖,没有什么“新”发生。 ES5 方法仍然有效。
  • @PaulS。 Syntactic Sugar ;)

标签: javascript class prototype ecmascript-6


【解决方案1】:

ECMA-Script 6 类语法是常规原型系统的语法糖:

class A {

}

// This is still possible!
A.prototype.doStuff = function() {

};

var existingFn = function() {};

A.prototype.existingFn = existingFn;

var instance = new A();
instance.existingFn();

【讨论】:

  • 请记住,未来会稍微复杂一些:Object.defineProperty(A.prototype, 'existingFn', {configurable:true, writable: true, enumerable: false, value: existingFn});。如果有一个具有此方法的父类,并且此方法将覆盖它,并且父属性是 getter/setter 或不可写,则您的示例可能失败。
  • @loganfsmyth 我试图为 OP 的简单场景提供解决方案。
【解决方案2】:

定义属性的“Es6方式”是使用构造函数

class MyClass {
  constructor() {
    this.existingFn = existingFn;
  }
}

【讨论】:

猜你喜欢
  • 2017-07-06
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多