javascript - Prototype: Difference between these two scripts -
consider these 2 version of constructing object hierarchies in javascript:
version 1
function employee() { this.name = "noname"; this.dept = "nodept"; }; function manager() { employee.call(this); this.reports = "nobody"; } //manager.prototype = object.create(employee.prototype); var m = new manager(); console.log(m.name);
version 2
function employee() { this.name = "noname"; this.dept = "nodept"; }; function manager() { //employee.call(this); this.reports = "nobody"; } manager.prototype = object.create(employee.prototype); var m = new manager(); console.log(m.name);
in first version, name
property accessible though don't use prototype inheritance (of course because of call()
method). in second version, comment out call()
, define prototype chain, , yet name
property inaccessible.
this leaves me wondering, then, why bother manager.prototype
?
note in constructor:
function employee() { this.name = "noname"; this.dept = "nodept"; }
when called as:
new employee();
name , dept properties added directly the new object assigned this. aren't inherited, directly on instance.
in first version, name property accessible though don't use prototype inheritance
because when do:
employee.call(this);
you adding name property directly instance of manager. isn't inherited, it's directly on instance.
in second version, comment out call() , define prototype chain, , yet name property inaccessible
because name property isn't on prototype chain, employee constructor puts directly on this (which instance of employee because of how call manager, it's instance of manager).
this leaves me wondering, then, why bother manager.prototype?
so instances of manager inherit employee.prototype. haven't added methods employee.prototype there's nothing inherit.
Comments
Post a Comment