Huy Nguyen
Huy Nguyen

Reputation: 106

Confused about Javascript Constructor and Prototype

So I'm trying to build a custom constructor to be used and I'm a little confused about the prototype part. I'm testing it and when I go to do a console.log(testVar.getHostname); it returns function as text.

So I have the following.

function nodeInfo(hostname) {
    this.hostname = hostname;
};

nodeInfo.prototype.getHostname = function() {
    return this.hostname;
};

var testVar = new nodeInfo("google.com");

console.log(testVar.getHostname);

Output is the following.

function () {
return this.hostname;
}

Any idea what I'm doing wrong here? Can the prototype method be outside of the constructor? I've seen it done that way on a bunch of articles from searching google. Such as http://www.phpied.com/3-ways-to-define-a-javascript-class/

Any help is greatly appreciated.

Upvotes: 1

Views: 40

Answers (1)

Phrogz
Phrogz

Reputation: 303549

You want console.log(testVar.getHostName()) to run the function.

Functions in JavaScript are first-class values. They can be referenced by variables, stored in an array, set as properties, etc. In this case you're asking it to print a string value for the function, which happens to be the source code in this case. You could also do:

console.log( typeof testVar.getHostName );
// "function"

To level up your knowledge, examine and ponder the output of the following:

var testVar = new nodeInfo("google.com");
hostName = "Global";
var f1 = testVar.getHostName;
var o = { f2: testVar.getHostName, hostName:"In Object" };

console.log( testVar.getHostName() );
console.log( f1() );
console.log( o.f2() );
f1.call( o );
o.f2.call( testVar );

Upvotes: 1

Related Questions