object - Private function in Javascript constructor is not accessible publicly -
i have person object
function person(first, last, age, eye) { this.firstname = first; this.lastname = last; this.age = age; this.eyecolor = eye; function sayname(){ var full=""; full="hello name "+this.firstname + " "+this.lastname; } } and have made instance of object
var raul = new person("raul","zamora","19","brown") i cannot figure out why function sayname not working. implementing such:
document.getelementbyid("sayname").innerhtml=raul.sayname(); where sayname defined id on html part.
it doesn't work because sayname function visible in scope of constructor (and totally useless).
to make function available on instances, use
person.prototype.sayname = function(){ var full="hello name "+this.firstname + " "+this.lastname; return full; // don't forget return string } for more details, suggest article mdn : introduction object-oriented javascript
Comments
Post a Comment