Search code examples
javascriptobjectprototype-programming

Why does combination constructor/prototype pattern return typeof being object?


I'm having a hard time understanding why typeof doesn't return MyObject on an instance of MyObject when using this constructor/prototype pattern - it's returning object on an instance created by new using the MyObject constructor after the prototype for MyObject has had it's constructor set to MyObject - can someone explain why?

function MyObject(foo, bar) {
  this.foo = foo;
  this.bar = bar;
}

MyObject.prototype = {
  constructor: MyObject,
  someFunc: function() {
    console.log(foo + " and " + bar);
  }  
}

var newObject = new MyObject("a", "b");
typeof newObject;

Solution

  • Use instanceof operator if you want to check that: newObject instanceof MyObject; (returns true)

    More info as to why typeof behaves like that: http://javascript.crockford.com/remedial.html