Reputation: 75
I have this 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 my name is "+this.firstName + " "+this.lastName;
}
}
and have made an instance of this object
var raul = new person("Raul","Zamora","19","brown")
I cannot figure out why the function sayName is not working. I am implementing it as such:
document.getElementById("sayName").innerHTML=raul.sayName();
where sayName
is already defined as an id on the HTML part.
Upvotes: 0
Views: 71
Reputation: 20014
Your function sayName
does not "belong" to your Class, in order to do so you need to declare it using this
or using propotype
Using this
:
function person(first, last, age, eye) {
this.sayName = function(){
return "Hello my name is "+this.firstName + " "+this.lastName;
}
}
Using prototype
:
person.prototype.sayName = function(){
return "Hello my name is "+this.firstName + " "+this.lastName;
}
Additionally sayName
was not returning anything.
Upvotes: 0
Reputation: 664599
You've got a local function declaration there. Make it a property of the object by assignment - just like you did write this.firstName = first
not var firstName = first
.
This will make it a method that is accessible from outside:
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.sayName = function sayName(){
var full="Hello my name is "+this.firstName + " "+this.lastName;
};
}
However, some objections:
sayName
method needs to return
the string, or your example invocation won't workSo we get to
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.sayName = function sayName(){
return "Hello my name is "+this.firstName + " "+this.lastName;
};
var raul = new Person("Raul","Zamora","19","brown");
document.getElementById("sayName").textContent = raul.sayName();
Upvotes: 0
Reputation: 382170
It doesn't work because that sayName
function is only visible in the scope of the constructor (and thus is totally useless).
To make that function available on instances, use
person.prototype.sayName = function(){
var full="Hello my name is "+this.firstName + " "+this.lastName;
return full; // don't forget to return the string
}
For more details, I suggest this article from the MDN : Introduction to Object-Oriented JavaScript
Upvotes: 2