简体   繁体   English

来自现有对象的新ES6类实例

[英]New ES6 class instance from an existing object

Is it possible in JavaScript to create a new ES6 class instance that would have access to properties of an existing object right within the constructor? 用JavaScript可以创建一个新的ES6类实例,该实例可以直接在构造函数中访问现有对象的属性吗?

I have an ES5 class: 我有一个ES5课程:

function ES5() {
    this.value = 123;
}

And I need to be able to create an ES6 class instance: 我需要能够创建一个ES6类实例:

class ES6 {
    constructor() {
        console.log(this.value); /* must print 123 */
    }
}

that would have access to the ES5 class properties from within the constructor. 可以从构造函数内部访问ES5类属性。

Basically, I want something like: 基本上,我想要这样的东西:

Object.create(ES6.prototype, new ES5());

though I know this code doesn't work. 尽管我知道这段代码行不通。 But is there a way to make this type of logic work? 但是有办法使这种逻辑起作用吗?


I have a library that accepts a function for creating new objects, and I have added a way to check if it is an ES6 class, to initialize it differently, with the new operand, while providing my own existing object for the class. 我有一个接受创建新对象的函数的库,并且添加了一种方法来检查它是否为ES6类,并使用new操作数对其进行不同的初始化,同时为该类提供我自己的现有对象。

NOTE: This also means that class ES6 has no knowledge of the ES5 class existence, only of its properties. 注意:这还意味着ES6类不了解ES5类的存在,而仅了解其属性。 Or to put it otherwise, class ES6 needs to get property value automatically, it cannot patch itself. 或者换句话说,类ES6需要自动获取属性value ,它无法修补自身。

more details 更多细节

My library executes new ES5() internally, while class ES6 is declared on the client side. 我的库在内部执行new ES5() ,而类ES6在客户端声明。 So they co-exist independently. 因此,它们独立地共存。 And when the client passes me in the ES6 class, I need to instantiate it in such a way that it thinks it extends class ES5 , ie has access to the extra properties. 当客户端通过我的ES6类时,我需要以使其认为扩展了ES5类的方式实例化它,即可以访问额外的属性。

function createClass(func) {
  if(/* func is an ES6 class*/) {
      var a = new ES5();
      return /* new ES6 instance that has access to ES5 object properties */
  } else {
      return new ES5();
  }
}

You can set the prototype of the class to the ES5 instance. 您可以将类的原型设置为ES5实例。 This will put the instance and the ES5 function in the prototype chain: 这会将实例和ES5函数放入原型链中:

 function ES5() { this.value = 123; } class ES6 { constructor() { console.log(this.value); /* must print 123 */ } } let e5 = new ES5() Object.setPrototypeOf(ES6.prototype, e5) let e6 = new ES6 // ES5 now in the prototype chain of e6 console.log("instance of ES5:", e6 instanceof ES5) console.log("instance of ES6:", e6 instanceof ES6) // they are linked by prototype (not sure if that's good or bad for your use): console.log("es6 value: ", e6.value) e5.value = "newValue" console.log("es6 value: ", e6.value) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM