|
|
|
|
|
by lhorie
4998 days ago
|
|
> `bar` DOES equal 5 No, it doesn't. Javascript is a bit weird when it comes to return statements inside constructors. `bar` will be equal to `type` only if `(type instanceof Object) == true`. Otherwise, it will be a new object. function Foo(type) { this.type = type; return type; }
console.log(new Foo(/a/)); // Regexp /a/
console.log(new Foo("a")); // {type: "a"}
console.log(new Foo(5)); // {type: 5}
console.log(new Foo([1,2])); // [1,2]
console.log(new Foo({a:1})); // {a: 1}
|
|
Almost all cases that I've used this functionality have been to return a different object. I suppose when you say "new" you're supposed to expect an object, which is why it works that way.