Home > Web Front-end > JS Tutorial > 9 JavaScript Traps and Comments Analysis_Javascript Skills

9 JavaScript Traps and Comments Analysis_Javascript Skills

WBOY
Release: 2016-05-16 19:04:26
Original
856 people have browsed it

1. The last comma

As in 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.



2. The reference of this will change

such as this code:




is not as good as As you might expect, the answer isn't "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:




Essentially, this is a problem with JavaScript scope. If you look, you'll see there's more than one solution.

3. Identity thieves
Do not use the same variable name as the HTML ID in JavaScript. The following code:





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

4. The string only replaces the first matching

as follows:

<script> <BR> var theObj = { <BR> city : "Boston", <BR> state : "MA", <BR> } <BR></script> <script> <BR>var MyObject = function () { <BR> this.alertMessage = "Javascript rules"; <BR> this.ClickHandler = function() { <BR> alert(this.alertMessage ); <BR> } <BR>}(); <BR>document.getElementById(”theText”).onclick = MyObject.ClickHandler <BR></script> And actually, the result is "This_is a title". In JavaScript, the first parameter of String.replace should be a regular expression. So, the correct approach is this: <script> <BR>var MyObject = function () { <BR> var self = this; <BR> this.alertMessage = “Javascript rules”; <BR> this.OnClick = function() { <BR> alert(self.value); <BR> } <BR>}(); <BR>document.getElementById(”theText”).onclick = MyObject.OnClick <BR></script><script> <BR> TheButton = get("TheButton"); <BR></script>var fileName = "This is a title".replace(/ /g,"_"); <script> <BR> var fileName = "This is a title".replace(" ","_"); <BR></script>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template