2

I have code following like this:

function Person() {
    this.name = '123';
    this.age = 123;
}
Person.prototype.load = function() {
    console.log(this.name + " test "); 
}
var p1 = new Person();
console.log(p1.load());

the console output two news. One is 123 test, the other is undefined.I wonder where is undefined comes from?

Todd Mark
  • 1,847
  • 13
  • 25

4 Answers4

1

The load functions returns nothing, that is it returns undefined. And you log this undefined here :

console.log(p1.load());

You probably just want

p1.load();
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

The return value of console.log is ALWAYS undefined. It prints to the console, but it doesn't actually return anything itself.

var tmp = 5;
console.log(tmp); // prints 5, returns undefined.
tmp; // Returns 5         

Also why are you printing out the result of a function that already prints out the information you want?

NMunro
  • 890
  • 5
  • 20
0

hi you do not need to take too much tension about that undefined. Your code is correct and it will work fine in any js file.

That undefined comes as you make instance of person class.

Sandip Vora
  • 183
  • 7
0

http://jsfiddle.net/5azsp5r9/

Here you go mister:

function Person() {
    this.name = '123';
    this.age = 123;
}
Person.prototype.load = function() {
    //Load started for John Doe 
    console.log("Load started for "+ this.name );   
    return "Load ended";
}
var p1 = new Person();
p1.name = "John Doe";
//Load ended 
console.log(p1.load());;
SilentTremor
  • 4,747
  • 2
  • 21
  • 34