4
function math() { return 'x' } 

math.prototype.sqrt = function(a){return Math.sqrt(a)} 

var x = new math(); 
x.sqrt(9); //gives 3

function math1() { return {} } 

math1.prototype.sqrt = function(a){return Math.sqrt(a)} 

var y = new math1(); 
y.sqrt(9); //throws javascript error "TypeError: Object #<Object> has no method 'sqrt'"
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
Narendra Yadala
  • 9,554
  • 1
  • 28
  • 43

1 Answers1

4

Normally there is nothing to be achieved from returning a value from an constructor. It seems that if a JavaScript primitive such as a number or string are returned, the object instantiation process with new (var y = new math1();) works as you would expect, ignoring this value.

However it seems if you return a JavaScript object such as {} the instantiation process with new doesn't work in the same way. Instead your variable y is loaded with the object returned not with a new instance of math1.

Jim Blackler
  • 22,946
  • 12
  • 85
  • 101