Convert objects: from literal syntax to prototype types

Asked

Viewed 204 times

4

Given a type defined in javascript, for example:

var Point = (function () {
    function Point(x, y) {
        this.x = x;
        this.y = y;
    }
    Point.prototype.dist = function () {
        return Math.sqrt(this.x * this.y + this.x * this.y);
    };
    return Point;
})();

That can be used this way:

var p = new Point(10, 20);
console.log(p.dist());

Or so:

var p = new Point();
p.x = 10;
p.y = 20;
console.log(p.dist());

There is a direct way to convert an object that is usually returned by JSON, or declared using literal syntax in this way:

var p = { x: 10, y: 20 };

For my kind Point that has the method dist() unused from = to?

1 answer

4


The only way to exchange the prototype of an existing object is with the non-standard property __proto__, which in practice has very good support. In the next version of Javascript (Ecmascript 6), there will be a function Object.setPrototypeOf for that. But today the way is to do so:

var p = { x: 10, y: 20 };
p.__proto__ = Point.prototype;
console.log(p.dist());

Demo

Another option is to invoke the method directly from the source location:

console.log(Point.prototype.dist.call(p));

Demo

  • I will use: p.__proto__ = Point.prototype;. In addition, to get an array to be converted only iterating each element or there is some different way?

  • If you have an array with these objects inside you need to iterate and assign the __proto__ one by one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.