0

I am new in JS programming and trying to understand prototype-based inheritance. below is my test code and I have a question about line method 'parseParameters'.

As I know, when I am instantiating class Point and wring following:

var p = new Point ({x: 1, y: 1});
alert(p.x);

member 'x' firstly searched in the Point class, then in its prototype (Shape). Is it right?

And question itself: where will be created members 'x' and 'y' - in the Point class or in Shape (prototype)?

One remark: should I actually thinking of it? Maybe it is negligible question and there is no matter where the member created?

var Shape = function () {}

Shape.prototype = {
    getParameter: function (params, name) {
        return params !== null && params !== undefined
            ? params[name]
            : 0;
    },

    parseParameters: function(params, names) {
        if (params === null || params === undefined) {
            return;
        }

        for(var i = 0; i < names.length; i++) {
            this[names[i]] = params[names[i]];
        }
    }
}

var Point = function (params) {
    this.parseParameters(params, ['x', 'y'])
}

Point.prototype = new Shape;
Alex G.P.
  • 9,609
  • 6
  • 46
  • 81

1 Answers1

0

p.x

member 'x' firstly searched in the Point class, then in its prototype (Shape). Is it right?

Apart from that there are no "classes" in JavaScript, yes. The property name will first be searched on the p object itself, then in the object it did inherit from (there's an internal link).

Where will be created members 'x' and 'y' - in the Point class or in Shape (prototype)?

Depends on how you create them :-)

In a simple assignment, like p.x = 1; (which also happens in parseParameters' this[names[i]] = params[names[i]], as this === p) the property will be created on the p object.

should I actually thinking of it? Maybe there is no matter where the member created?

No, that really matters. If you would create them on the prototype object, all objects which inherit from that one would share the same values. While this is useful for the functions, it would be catastrophic for data properties like x and y which should differ from instance to instance (see also Why are my JavaScript object properties being overwritten by other instances? for an example).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375