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'"
Asked
Active
Viewed 347 times
4

Klaus Byskov Pedersen
- 117,245
- 29
- 183
- 222

Narendra Yadala
- 9,554
- 1
- 28
- 43
-
Nice question. I learned something today. – MAK Apr 02 '11 at 12:36
1 Answers
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