Home  >  Article  >  Web Front-end  >  9 pitfalls and comments about JavaScript

9 pitfalls and comments about JavaScript

黄舟
黄舟Original
2016-12-14 15:51:12867browse

From Nine Javascript Gotchas, the following are nine common pitfalls of JavaScript. Although it is not a very deep technical issue, paying attention will make your programming easier, which is called making life easier. The author will have mixed comments on some traps.

The last comma

Like this code, pay attention to the last comma, which should be good from a linguistic point of view (python's dictionary of similar data types allows this). IE will report syntax errors, but the language is unclear. You can only scan thousands of lines of code with human eyes.

<script> var theObj = { city : "Boston", state : "MA", }</script> The reference of this will change

such as this code:

<script>var MyObject = function () { this.alertMessage = "Javascript rules"; this.ClickHandler = function() { alert(this.alertMessage ); }} ();document.getElementById("theText").onclick = MyObject.ClickHandler</script>

is not what you want, the answer is not "JavaScript rules". When executing MyObject.ClickHandler, in the red line of code, the reference of this actually points to the reference of document.getElementById("theText"). It can be solved like this:

<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, this is JavaScript scope The problem. If you look, you'll see there's more than one solution.

Identity Thief

Don’t use variable names in JavaScript that are the same as HTML ids. The following code:

<script> TheButton = get("TheButton");</script>

IE will report an object undefined error. All I can say is: IE sucks.

The string only replaces the first match

The following code: