The first glance at JavaScript

>>在哪里放置 JavaScript

 JavaScript可以放置在Head或者Body之中,也可以从外部引用。

HTML内嵌JavaScript

<html>
<head>
<script type="text/javascript">
document.write("<h1>This is a header</h1>"); 
</script>
</head>

<body>
<script type="text/javascript">
document.write("<p>This is a body</p>");
</script>
<script type="text/javascript">
//Write a "Good afternoon" greeting if
//the time is larger than 12
var d=new Date()
var time=d.getHours()
if (time>12) {
    document.write("<b>Good afternoon</b>");
}
</script> </body> </html>

外部引用JavaScript

把 .js 文件放到网站目录中通常存放脚本的子目录中,这样更容易管理和维护。

<html>
<head>
<script type="text/javascript" src="externaljs.js">....</script>
</head>
<body>
</body>
</html>

 不过,从Performance的角度来看,无论是哪种方式,都放尽量发在Html Body的最后部分,免得Loading JavaScript会block影响整个html页面的loading。

>> Values/Types

Booleans: true/false

Numbers: 1, 1.0

Strings: "abc", 'abc'

Functions:

    function twice(x) {
        return 2 * x;
    }
    console.log(twice(4)); // 8

Objects:

var obj = {
        propName1: 123,
        propName2: "abc"
};
obj.propName1 = 456;
obj["propName1"] = 456; // same as previous statement

Arrays:

var arr = [true, "abc", 123];
console.log(arr[1]); // abc
console.log(arr.length); // 3

undefined

null

>>条件控制

 if- else if - else:

<script type="text/javascript">

var d = new Date();
var time = d.getHours();

if (time<10){
    document.write("<b>Good morning</b>");
}
else if (time>10 && time<16){
   document.write("<b>Good day</b>");
}
else{
   document.write("<b>Hello World!</b>");
}
</script>

switch - case

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();
theDay=d.getDay();

switch (theDay) {
   case 5:
     document.write("Finally Friday")
     break
   case 6:
     document.write("Super Saturday")
     break
   case 0:
     document.write("Sleepy Sunday")
     break
   default:
     document.write("I'm looking forward to this weekend!")
}
</script>

 >>循环控制

 for loop:

<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++){
    document.write("The number is " + i);
    document.write("<br />");
}
</script>

while:

<script type="text/javascript">
var i=0
while (i<=10){
    document.write("The number is " + i);
    document.write("<br />");
    i=i+1;
}
</script>

do-while:

<script type="text/javascript">
var i=0
while (i<=10){
    document.write("The number is " + i);
    document.write("<br />");
    i=i+1;
}
</script>

for ... in:

<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars){
    document.write(mycars[x] + "<br />");
}
</script>

break - continue:

<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++){
    if (i == 3){
       break;
    }

    if(i == 4){
        continue;
    }

    document.write("The number is " + i);
    document.write("<br />");
}
</script>

>> Event

onload/onUnload:

    onload在导入页面的时候触发,而onUnload则是在退出的时候触发。

onFocus, onBlur 和 onChange:

    通常相互配合用来验证表单。

onSubmit

    用于在提交表单之前验证所有的表单域。

onMouseOver 和 onMouseOut

    常用来用来创建“动态的”按钮。

>> Error Handling

Exception(try/catch, throw):

<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
  {
    if(x>10)
        throw "Err1"
    else if(x<0)
        throw "Err2"
  }
catch(err)
  {
      txt="Unexcepted error found\n\n"
      txt+="Description: " + err.description + "\n\n"
      txt+="Choose OK to continue.\n\n"
      alert(txt)
  }
}
</script>
</head>

onerror:

<html>
<head>
<script type="text/javascript">
onerror=handleErr
var txt=""

function handleErr(msg,url,l){
    txt="There was an error on this page.\n\n";
    txt+="Error: " + msg + "\n";
    txt+="URL: " + url + "\n";
    txt+="Line: " + l + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
    return true;
}

function message(){
adddlert("Welcome guest!");
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

>> High Performance JavaScript

1. Always prefer the Single var pattern.

JavaScript Engine hosts all the vars to the top of the function. So even if we declare our var at the bottom of the function, it doesn’t matter.

function foo() {
    var c = 1;
    //lots of logic
    //and then
    var d = 0;
var e;
}
 
function foo() {
    var c = 1, d = 0, e;

}

2. Cache your objects whenever possible.

Piaoger在jsperf试过,把length存起来还是很有用的,大约有10%的性能差异。

//Good
for (var i = 0, x = p.length; i<x; i+=1) {
    
}
//Better
for (var i = 0, x; x= p[i]; i += 1) {
 
}

3. Avoid memory leaks and circular references in your closures.

From:

//Classic case for circular references
function foo(e,d) {
    $(e).on("click", function() {
        //Do something with d
    });
}

To:

//Break the cycle!
function foo(e, d) {
$(e).on(
"click", cbk(d)); } function cbk (d) { }

4. Move common functions to prototype:

Everytime you create a new person, JS Engine allocates memory for firstName, lastName and getName. I don't mean to say that this is wrong but this is inefficient. Isn't it? So, what's the solution? Move getName to prototype!

From:

function Person(fname,lname) {
    this.firstName = fname;
    this.lastName = lname;
 
    this.getName = function(){
        return this.firstName + ' ' + this.lastName;
    }
 
}
//lets say you are doing something like this in your code
var p1 = new Person("Jack", "Smith");
var p2 = new Person("John", "Doe");

To:

//Better
Person.prototype = {
   getName : function(){
       return this.firstName + ' ' + this.lastName;
   }
}

5. How to clean a array

 //lets try the cleanup differently!
 arr.length = 0;

6. Avoid anonymous functions inside setTimeout or setInterval之类的函数或者循环内

JS Engine simply creates a new anonymous function every 2 seconds! More garbage and you know the consequence! The solution is obviously to use a named function and reference it inside setTimeout.

From:

setTimeout(function(){ 
    //do Something
  }, 2000);

To:

//Much better
  function myCallback(){ 
    //do Something
  };
  setTimeout(myCallback, 2000);

7, Using static classes

See if you can get away by using Static classes in your app. Use instance classes only when necessary. The idea is to use memory sparingly - only when it's an absolute necessity.

//Simpler and better
   var MyApp = MyApp || {};
   MyApp = (function () {
    var doSomething = function() { }
    return {
        init: function (a) {
            
        };
    };
})();
MyApp.init();

From

>> More Materials:

JavaScript: The good part

Javascript 编程风格

JavaScript内存泄露

JavaScript W3C School

A quick overview of JavaScript

Major and minor JavaScript pitfalls and ECMAScript 6

 

 

原文地址:https://www.cnblogs.com/piaoger/p/2486807.html