As the title said, or can I just use them directly without any declaration? (It seems a dumb question, but I want to make sure nothing goes wrong in these subtle aspects.)
5 回答
Nope. Everything that is apart of Javascript is automatically included.
No. What's built in to the browser is there automatically. There are obviously differences browser to browser as to what's built in, but most browsers today implement a common core set.
As everyone else has said, you don't have to add anything. Each browser has its differences when it comes to javascript implementation and that is why libraries such as jQuery are popular. They as the abstract away these differences.
Unfortunately, not all browsers have every single method available (especially older ones). In those cases, there are plenty of solutions that people post that you can include in your script to fix it. For example, the .indexOf() method for arrays is not available in older versions of IE. But, there's a very simple function you can write, such as:
if (!Array.indexOf) {
// Replaces the "indexOf" method for arrays when not available.
// Used like array_var.indexOf(int)
Array.prototype.indexOf = function (obj) {
for (var i=0; i < this.length; i++) {
if (this[i] == obj) {
return i;
}
}
return -1;
}
}
There are newer methods that help ease the use of JSON but are not available in older browsers. Those, as well, have simple functions that people have written for you to include in case the browser doesn't support it.
So for the most part, for probably all of the types, methods, functions and anything else that you want to use that is a part of Javascript is available for you to use without any importing, including or declaration.
No, but you need to be aware that not all environments have the same "built-in" functions...
Assuming you target web browsers, depending on the browser and its version number you won't get the all the same features.
For instance, array manipulation functions like .map()
, or JSON manipulation functions like JSON.parse()
, are relatively new additions that are now mainstream across modern browsers, but weren't guaranteed to be there only a few years back.
So be careful, depending on your target platforms.
You can, however, then use different libraries to add the missing functionalities, or to wrap them (one of my favorite "toolkit/utilities" library would be underscore.js, for instance, or dojo.js for more heavyweight stuff. Other prefer jQuery, or Prototype, etc...). These will often delegate to built-in functions, if present, or use their own implementation if needed, saving you from having to check for a function's existence.