See this code of prototypal inheritance:
var Person = function() {
this.canTalk = true;
};
Person.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name);
}
};
var Employee = function(name, title) {
Person.call(this);
this.name = name;
this.title = title;
};
Employee.prototype = Object.create(Person.prototype);
// Note: there's no difference, when I comment out the following line
Employee.prototype.constructor = Employee;
Employee.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name + ', the ' + this.title);
}
};
var bob = new Employee('Bob', 'Builder');
bob.greet();
I do get the same result (console output) even if I comment out the line
Employee.prototype.constructor = Employee;
Then what is worth of equalizing the function prototype constructor to function itself. I am a newbie in JS. Also if it effects in long run. How? I do not want any workarounds.
Then what is worth of equalizing the function prototype constructor to function itself.
There is some intrinsic worth to it and some practical use.
Firstly, setting the correct constructor on the derived class's prototype keeps things symmetric. What this means is, the property .constructor
serves the purpose of intuitively suggesting which function created this object.
var Person = function() {};
var Employee = function() {};
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
var bob = new Employee();
console.log(bob.constructor);
console.log(bob.__proto__.constructor);
console.log(bob.__proto__.__proto__.constructor);
console.log(bob.__proto__.__proto__.__proto__.constructor);
// [Function: Employee]
// [Function: Employee]
// [Function: Person]
// [Function: Object]
var Person = function() {};
var Employee = function() {};
Employee.prototype = Object.create(Person.prototype);
// Employee.prototype.constructor = Employee;
var bob = new Employee();
console.log(bob.constructor);
console.log(bob.__proto__.constructor);
console.log(bob.__proto__.__proto__.constructor);
console.log(bob.__proto__.__proto__.__proto__.constructor);
// [Function: Person]
// [Function: Person]
// [Function: Person]
// [Function: Object]
Secondly, if you need to use the constructor function, you can use it from the .constructor
reference, rather than using the function name. This point is elaborated upon in this asnwer: https://stackoverflow.com/a/8454111/1343488
I am a newbie in JS.
I recommend you visit the website: http://www.javascripttutorial.net/
It is a great site to study up on JS concepts.