spssps spssps - 3 months ago 8
Javascript Question

javascript prototype method returns a string value

I am new to javascript.
While learning on object's prototype, i encountered with the below example.

function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

Person.prototype.name = function() {
return this.firstName + " " + this.lastName
};

var myFather = new Person("John", "Doe", 50, "blue");
alert(myFather.name);


When i tried to run via browser using html page, the following alert message popped up.

function() {
return this.firstName + " " + this.lastName
}


So, instead of returning 'John Doe', it returns the entire function as a string.
How to resolve this?

PS: I use VS Code, and i use node.js live-server to run in browser.

Answer

You need to execute the function by this way myFather.name()

var myFather = new Person("John", "Doe", 50, "blue");
alert(myFather.name());

JSFIDDLE