开发者

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() {
    c开发者_开发问答onsole.log(foo + " and " + bar);
  }  
}

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


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


typeof only returns "object", see https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof

What you probably want is this: How to get a JavaScript object's class?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜