简体   繁体   中英

Is it possible to make an already initialised object literal an instance of a defined class?

I would like to know if it is possible to make an already initialised object literal into an instance of an already defined class.

class ParentClass {
   bye () { console.log("Bye!"); }
}

class ChildClass extends ParentClass { 
   hello () { console.log("Hello!"); }
}

let obj = { foo: function (){ console.log("foo foo!"); } }

// [JS code that i wish i knew] //

obj.hello() // "Hello!" 
obj.bye() // "Bye!"
obj.foo() // "foo foo!"

console.log(obj instanceof ChildClass) // true

There's already a method for this - setPrototypeOf :

 class ParentClass { bye() { console.log("Bye!"); } } class ChildClass extends ParentClass { hello() { console.log("Hello!"); } } let obj = { foo() { console.log("foo foo!"); } }; Object.setPrototypeOf(obj, ChildClass.prototype); obj.hello(); obj.bye(); obj.foo();

An "initialised object literal" is just an object, how it was created is generally not important beyond the moment it's created. Objects created as if by Object.create or new Object() (such as literals) are generally called "plain objects".

ECMAScript doesn't have classes, it has prototype inheritance and a class syntax to instantiate objects that inherit from a particular constructor's prototype.

So if you want a plain object to inherit methods from a particular object's prototype without using the constructor to make the object, you can assign the required constructor's prototype to the plain object's [[Prototype]] using Object.setPrototypeOf .

However, you might be better off to construct a new instance of the "class" you want and copy the plain object's properties to it using Object.assign , something like:

 class Person { constructor (name, age) { this.name = name; this.age = age; } } let obj = { name: 'fred', age: '37' }; let person = Object.assign(new Person(), obj); console.log(person.name);

Is it what you want ? The obj is declared with the new keyword...

obj = Object.assign(obj, { foo: function (){ console.log("foo foo!"); } } );

Tested, it will do the work, the trick is Object.assign :

class ParentClass {
   bye () { console.log("Bye!"); }
}

class ChildClass extends ParentClass { 
   hello () { console.log("Hello!"); }
}

let obj = { foo: function (){ console.log("foo foo!"); } }

// [JS code that i wish i knew] // here is how it works
obj = Object.assign(new ChildClass(), obj)

obj.hello() // "Hello!" 
obj.bye() // "Bye!"
obj.foo() // "foo foo!"

console.log(obj instanceof ChildClass) // true

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