javascript prototype declaration -
there 2 pieces of codes.
why first 1 correct second 1 incorrect?
what's wrong this.prototype
?
function person(name, age, job){ this.name = name; this.age = age; this.job = job; if (typeof this.sayname != "function"){ person.prototype.sayname = function(){ alert(this.name); }; } }
function person(name, age, job){ this.name = name; this.age = age; this.job = job; if (typeof this.sayname != "function"){ this.prototype.sayname = function(){ alert(this.name); }; } }
both of them incorrect. more on later.
the second 1 incorrect because objects don't have prototype
property. only functions have such property.
in second example, this
object, this.prototype
undefined
. in first example setting person.prototype
, person
function, "good".
why first example still wrong? because don't have reason extend prototype object inside constructor. constructor should contain instance specific code , prototype object should hold properties shared instances.
so above example correctly written as:
function person(name, age, job){ this.name = name; this.age = age; this.job = job; } person.prototype.sayname = function(){ alert(this.name); };
Comments
Post a Comment