Forgive me if I'm wrong, but I thought that by doing this:
function MyObject()
{
return {
key: 'value',
hello: function() { console.log('world'); }
};
}
var obj = new MyObject();
I create a new instance of the MyObject type.
However, if I do this:
obj instanceof MyObject
It returns false. This baffles me, as I thought that this would return true.
What am I doing wrong here?
Here's a fiddle that tests this.
I thought that I new the basics of JavaScript, but perhaps not. However, I've found sources that contradict my findings.
If you explicitly return an object from a constructor function (as you do here) then you get that object instead of an instance of the constructor.
If you wanted to get an instance of the constructor, then you would do this:
function MyObject()
{
this.key = 'value';
this.hello = function() { console.log('world'); };
}
(Although, in general, you'd want to put methods on the prototype instead of generating duplicates of them each time you construct a new instance).
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