Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prototype and constructor object properties

I've:

function Obj1(param)
{
    this.test1 = param || 1;

}

function Obj2(param, par)
{
    this.test2 = param;

}

now when I do:

Obj2.prototype = new Obj1(44);
var obj = new Obj2(55);

alert(obj.constructor) 

I have:

function Obj1(param) {
    this.test1 = param || 1;
}

but the constructor function has been Obj2... why that? Obj1 has become the Obj2 prototype...

Can someone explain me, in detail, the prototype chain and the constructor property

Thanks

like image 376
xdevel2000 Avatar asked Feb 12 '09 13:02

xdevel2000


2 Answers

constructor is a regular property of the prototype object (with the DontEnum flag set so it doesn't show up in for..in loops). If you replace the prototype object, the constructor property will be replaced as well - see this explanation for further details.

You can work around the issue by manually setting Obj2.prototype.constructor = Obj2, but this way, the DontEnum flag won't be set.

Because of these issues, it isn't a good idea to rely on constructor for type checking: use instanceof or isPrototypeOf() instead.


Andrey Fedorov raised the question why new doesn't assign the constructor property to the instance object instead. I guess the reason for this is along the following lines:

All objects created from the same constructor function share the constructor property, and shared properties reside in the prototype.

The real problem is that JavaScript has no built-in support for inheritance hierarchies. There are several ways around the issue (yours is one of these), another one more 'in the spirit' of JavaScript would be the following:

function addOwnProperties(obj /*, ...*/) {
    for(var i = 1; i < arguments.length; ++i) {
        var current = arguments[i];

        for(var prop in current) {
            if(current.hasOwnProperty(prop))
                obj[prop] = current[prop];
        }
    }
}

function Obj1(arg1) {
    this.prop1 = arg1 || 1;
}

Obj1.prototype.method1 = function() {};

function Obj2(arg1, arg2) {
    Obj1.call(this, arg1);
    this.test2 = arg2 || 2;
}

addOwnProperties(Obj2.prototype, Obj1.prototype);

Obj2.prototype.method2 = function() {};

This makes multiple-inheritance trivial as well.

like image 114
Christoph Avatar answered Sep 22 '22 17:09

Christoph


Check out Tom Trenka's OOP woth ECMAscript, the "Inheritance" page. Everything from the prototype is inherited, including the constructor property. Thus, we have to unbreak it ourselves:

Obj2.prototype = new Obj1(42);
Obj2.prototype.constructor = Obj2;
like image 26
gustafc Avatar answered Sep 20 '22 17:09

gustafc