Convert objects: from literal syntax to prototype types

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 normally returned by JSON, or declared using literal syntax in this way:

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

For my type Point that has method dist() without using from = to ?

    
asked by anonymous 03.05.2014 / 17:18

1 answer

4

The only way to switch the prototype of an existing object is with the non-default property __proto__ ", which in practice has very good support. In the next version of JavaScript (ECMAScript 6), there will be a Object.setPrototypeOf function for this. 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 call the method directly from the source location:

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

Demo

    
03.05.2014 / 17:59