Can I set the type of a Javascript object?

后端 未结 5 1452
忘了有多久
忘了有多久 2021-02-02 00:15

I\'m trying to use some of the more advanced OO features of Javascript, following Doug Crawford\'s \"super constructor\" pattern. However, I don\'t know how to set and get types

5条回答
  •  迷失自我
    2021-02-02 00:38

    In my opinion, in a properly designed type heirarchy, you don't need to know the types of the individual objects. But I seem to be in the minority on that point.

    If you must have type identification, make it explicit.

    MyClass.prototype.type = "MyClass";

    It is reliable and portable, at least for your objects. It also works across contexts. DOM objects are another matter, although you can make things easier for yourself with

    window.type = "window";

    and so on.

    I believe the quote above was written by Douglas Crockford.

提交回复
热议问题