views:

30

answers:

2

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?

A: 

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 new operator returns a primitive, the this value will be returned.

If an object is returned, like in your second example (which IMO is not really useful), the newly created object (this within the constructor) will be lost, and you get an error because it doesn't contain a property named getDetails.

For example:

function Test () {
  // don't return anything (equivalent to returning undefined)
}

new Test() instanceof Test; // true

function Test2 () {
  return {};
}

new Test2 instanceof Test2; // false
CMS
thank you for your quick response...
Aneesh
A: 

This is because constructors:

  • automatically return the new this object if no manual return is specified
  • return another object of your choice if returned manually

However, you can't manually return a primitive value from the object, such as a raw string, number or boolean. You can get around this by Object-wrapping the value so that it's actually a String object:

return new String("hii");
Delan Azabani
thank you delan..
Aneesh