Hi so I'm finding that often want to include some or all of the following in my js projects:
- Crockford's Object.create
- Array.prototype.indexOf
- Array.prototype.remove
- Crockford's json2.js
see full example file @ https://gist.github.com/752895
so the question(s) .... what am I missing? Is there a better way to achieve this?
( I开发者_如何学编程 also use jquery, does it already address some of these issues? )
jQuery has a few functions like $.inArray()
, which works like Array.prototype.indexOf()
and $.parseJSON()
, which works like JSON.parse()
but it doesn't have an equivalent for stringifying JSON or removing elements from an array (to my knowledge). jQuery maps to the native methods if they are available.
You might want to check out Kris Kowal's ECMAScript 5 shim and see if there any other methods you might need that have native equivalents in modern browsers. This gives you the best of both worlds - compatibility in older browsers and better performance in newer ones.
Is there a better way to achieve this?
Not really. jQuery is intentionally hands-off things like the Array.prototype
, hence your having to add your own indexOf
and remove
on browsers that don't have them. Evetually most of these will be directly supported by browsers as they upgrade their engines to ECMAScript 5th edition; until then, we have to upgrade the current set ourselves. Just make sure your script is clean, combine it with other scripts in your application as part of a build process (so you don't have lots of different source files), and go to town. (Edit: Sorry, you clearly already undestand that latter point, as you've folded json2.js into your script.)
You might find it worth your while to learn to use a module loader such as RequireJS. This will make it tad easier for you to manage your dependencies. There are some basic instructions available in case you want to look at it.
As an additional benefit the loader makes it possible for you to minify your code via Google Compiler. Also the module pattern the loader uses is quite nifty.
精彩评论