Javascript Why assign a function prototype constructor to work? Programmer.prototype.constructor = Programmer

Here's the code for that

function Person() {
    this.klass = 'human';
}

Person.prototype.toString = function () {
    return this.klass;
};

Person.prototype.greeting = function () {
    return 'hello everyone Im ' + this.name + ', my job is ' + this.klass + '。';
};

function Programmer(name) {
    this.name = name;
    this.klass = 'coder';
}

Programmer.prototype = new Person();
Programmer.prototype.constructor = Programmer;


var someone = new Programmer('sam');

someone.name;          // sam
someone.toString();    // coder
someone.greeting();    // hello everyone Im sam my job is coder

      

I saw this piece of code from an online tutorial, but I'm wondering what is the purpose of this assignment:

Programmer.prototype.constructor = Programmer;

Ive tried deleting this job and everything is working fine.

+3


source to share


2 answers


There are very few differences. One thing to note is that quite often type checking (something that Javascript doesn't do well when trying to mimic OOP) is done by checking a property .constructor

. You are testing if (someone.constructor === Programmer)

.

If you remove the line Programmer.prototype.constructor = Programmer;

then someone.constructor

actually Person

, so when you check if they are Programmer

, it will fail.



Assigning a function Programmer

back as a method .constructor

returns that functionality to you.

To verify this, just add console.log( someone.constructor === Programmer, someone.constructor === Person );

to the end of your script, then try removing and adding that line.

+1


source


The property constructor

is in the prototype object, which in turn refers to your object. when you modify the prototype object by doing this Programmer.prototype = new Person();

, the constructor property stored in the actual prototype is lost because you are overwriting the prototype object itself.

so this line Programmer.prototype.constructor = Programmer;

will ensure that you fall back to the correct constructor (in other words, the correct parent object from which you created the object).

Not a big deal except for some debugging purposes to find out about the actual object from which the new object was created. It should be noted that it is easy to rewrite it to



Programmer.prototype.constructor = Tester;

      

Special care should be taken if any of your functionality depends on a constructor property to identify the actual parent, as this is not fool proof.

+1


source







All Articles