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)
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation).
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. ...
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With