When the myClass function returns a single string “hii”, testClass.getDetails() works fine:
function myClass(name, age) {
this.name = name;
this.age = age;
return "hii";
}
myClass.prototype.getDetails = function() {
return "mydetails";
}
var testClass = new myClass('aneesh', 27);
alert(testClass.getDetails());
But when I return an object in myClass:
function myClass(name, age) {
this.name = name;
this.age = age;
return {};
}
I get an error:
testClass.getDetails is not a function
Why does that happen? In Javascript a string is also an object, right?
No, a string literal like the one you are returning (
"hii") is a primitive value is not an object.In JavaScript we have the following primitives: string, number, boolean, undefined and null.
If a constructor used with the
newoperator returns a primitive, thethisvalue will be returned.If an object is returned, like in your second example (which IMO is not really useful), the newly created object (
thiswithin the constructor) will be lost, and you get an error because it doesn’t contain a property namedgetDetails.For example: