spssps spssps - 1 year ago 61
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");

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 Source

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

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download