9 Pitfalls of JavaScript and analysis of _javascript techniques
Source: Internet
Author: User
1. Last comma
As with this code, note the last comma, which should be a good linguistic point (as Python's Dictionary of Data Type Dictionary allows). IE will report grammatical errors, but vague, you can only employ eyes from thousands of lines of code scan.
<script>
var theobj = {
City: "Boston",
State: "MA",
}
</script>
2. This reference will change
such as this code:
<input type= "button" value= "gotcha!" id= "MyButton" >
<script>
var MyObject = function () {
This.alertmessage = "Javascript rules";
This. ClickHandler = function () {
alert (this.alertmessage);
}
}();
document.getElementById ("TheText"). onclick = Myobject.clickhandler
</script>
Not as you would like, the answer is not "JavaScript rules." When the Myobject.clickhandler is executed, the red line in the code, where the reference to this actually points to a reference to document.getElementById ("TheText"). Can solve this:
<input type= "button" value= "gotcha!" id= "TheText" >
<script>
var MyObject = function () {
var self = this;
This.alertmessage = "Javascript rules";
This. OnClick = function () {
alert (Self.value);
}
}();
document.getElementById ("TheText"). onclick = Myobject.onclick
</script>
Essentially, that's the problem with JavaScript scopes. If you've seen it, you'll find more than one solution.
3. Identification of thieves
Do not use the same variable names as HTML IDs in JavaScript. The following code:
<input type= "button" id= "Thebutton" >
<script>
Thebutton = Get ("Thebutton");
</script>
IE will report an undefined error to the object. I can only say: IE sucks.
4. String only replaces first match
The following code:
<script>
var fileName = "This is a title". Replace ("", "_");
</script>
In fact, the result is "this_is a title". In JavaScript, the first argument for String.Replace should be a regular expression. So the right thing to do is to:
var fileName = "This is a title". Replace (//g, "_");
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service