How to extend Obect.prototype correctly?

后端 未结 2 1761
孤街浪徒
孤街浪徒 2021-01-15 18:56

I\'m writing a JavaScript Library that offers the function tablify(anything);, which is able to represent any Array or Object as an HTML Table.

Now I\'

2条回答
  •  不知归路
    2021-01-15 19:22

    Why is typeof always returning "object"?

    Because in sloppy mode, the this context always is supposed to be an object. When you call a function or pass undefined or null, you get the global object, when you call a method the context will get casted to an object.

    Use strict mode for your tablify method and it will work!

    Is it a good thing for a JS-API to provide this sort of functionality (extending Arrays/Objects with .tablify();)?

    Yes. No.. Many people will frown to use your script when you want to share it. See Why is extending native objects a bad practice? for a detailed discussion.

    At least you've properly used non-enumerable properties - but I would recommend to use them on Array.prototype as well, too many people abuse for in enumerations.

    How is it possible to distinguish between "normal" objects, numbers, functions,... ?

    typeof seems fine.

    Is it possible to only extend "normal" objects? (forbid (42).tablify();, "string".tablify(); ...)

    Not really. All primitive wrappers inherit from Object.prototype.

    Whats the name for those "normal" objects? How should I call them?

    Just "objects". Or "plain objects" if you want (distinguishes them from arrays, built-ins, host objects).

提交回复
热议问题