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>