Lion King Lion King - 4 months ago 19
Javascript Question

What is the benefit of a constructor property in javascript?


  • What is the benefit of a constructor property ?

  • Is it resemble the constructor that in class base in c++ in behavior ?

  • What is the intended of the following ?






obj2.prototype.constructor = obj;


The complete Code:

var obj = function () {
this.str = "hello world!.";
obj.prototype.printTxt = function () {
console.log(this.str);
};
};

var obj2 = function () {
this.str = "Good bye";
};

obj2.prototype = new obj;
obj2.prototype.constructor = obj;

Answer Source

The constructor property is just a convention in JavaScript (that's no longer true as of ES2015); it points to the function that is associated with the prototype on which the constructor property exists. That's a bit of a convoluted sentence, so: Assume a function Foo. Foo.prototype.constructor will be Foo. Similarly, assuming var f = new Foo();, f.constructor will be Foo.

It's not actually used for anything in the JavaScript standard. (It is as of ES2015, for things like various Promise methods.) It's just a convention that, unless someone messes it up (which is easy to do), an object will have a constructor property it inherits from its prototype that is the function used to create it.

I say it's easy to break that because, well, it is, and people frequently do. Here's an example of breaking it:

function Foo() {
}
Foo.prototype = {
    bar: function() {
    }
};

var f = new Foo();
console.log(f.constructor === Foo); // false

The code you've quoted is very unusual for JavaScript:

  1. Most importantly, it breaks a hugely important rule: You don't change properties on the prototype from within the constructor (except in very edge-case scenarios). (Although in this particular case, it does so in a harmless but pointless way.)

  2. It breaks a fundamental naming rule in JavaScript: That constructor functions start with a capital letter (Obj, not obj).

  3. And it shows an all-too-common, but fundamentally broken, pattern for setting up inheritance hierarchies.

So on the whole, I would probably not use whatever resource it was that you got that code from.

FWIW, here's a corrected version of that code:

function Base() {
    this.str = "hello world!.";
}
Base.prototype.printTxt = function () {
    console.log(this.str);
};

function Derived() {
    this.str = "Good bye";
}

Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;

Object.create was defined by ECMAScript5. This single-argument version of it can be shimmed for older engines (the multi-argument version of it cannot be), like this:

if (!Object.create) {
    Object.create = function(proto) {
        if (arguments.length > 1) {
            throw "The multi-argument version of Object.create cannot be shimmed.";
        }

        function ctor() { }
        ctor.prototype = proto;

        return new ctor();
    };
}