简体   繁体   中英

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?

I have an ES5 class:

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

And I need to be able to create an ES6 class instance:

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

that would have access to the ES5 class properties from within the constructor.

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.

NOTE: This also means that class ES6 has no knowledge of the ES5 class existence, only of its properties. Or to put it otherwise, class ES6 needs to get property value automatically, it cannot patch itself.

more details

My library executes new ES5() internally, while class ES6 is declared on the client side. 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.

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. This will put the instance and the ES5 function in the prototype chain:

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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