Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an object literal to make an instance of a class without useing the constructor in JavaScript ES6?

I am trying to learn JavaScript ES6 which is a very cool language and I thought that I should practice a bit but I am not able to make an exercise. So how can I use object literal to copy a class.

For example the class is:

class Point {
  constructor(x, y) {
    this.x = x, this.y = y
  }
  add(other) {
    return new Point(this.x + other.x, this.y + other.y)
  }
}

And I want to do something here using object literal to make the output true.

var fakePoint = YOUR_CODE_HERE
console.log(fakePoint instanceof Point)
like image 376
Raghuveer Singh Bhardwaj Avatar asked Dec 19 '17 06:12

Raghuveer Singh Bhardwaj


People also ask

Can an object is created using literal?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation).

Which JavaScript feature is the alternative to the ES6 classes?

Top Alternatives to ES6 js or Apache CouchDB. It is a prototype-based, multi-paradigm scripting language that is dynamic,and supports object-oriented, imperative, and functional programming styles. ...

How do you instantiate a class in JavaScript?

An instance is an object containing data and behavior described by the class. The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.


1 Answers

I'll guess that this exercise is looking for a solution that uses __proto__ as an object literal key - as mentioned in the slides:

var fakePoint = {
    __proto__: Point.prototype,
    x: Math.random(),
    y: Math.random()
};
console.log(fakePoint instanceof Point)

However, __proto__ is deprecated (both in object literals and as a Object.prototype getter / setter) and only available in web browsers as a ES6-standardised legacy feature, so I recommend to avoid such code. The proper solution is to use Object.create:

var fakePoint = Object.assign(Object.create(Point.prototype), {
    x: Math.random(),
    y: Math.random()
});
console.log(fakePoint instanceof Point)
like image 53
Bergi Avatar answered Oct 18 '22 22:10

Bergi