I found something very odd today: If you create objects with a constructor function and the new
keyword, but return
a function from the constructor, it behaves like so:
this
in the constructor function, this
references an object that was correctly created from the constructor. It's what you expected to be returned from new
.Here's an example:
function Constructor() {
var self = this;
this.name = 'instance';
return function() {
return self;
}
}
So if you instantiated it like this: var instance = new Constructor()
The following would result:
typeof instance //returns "function"
typeof instance() //returns "object"
instance() //returns { name: 'instance' }
So I guess I have three questions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With