實用的JavaScript技巧、竅門和最佳實踐

1 – 在第一次給一個變量賦值的時候不要忘記使用var關鍵字javascript

給一個未定義的變量賦值會致使建立一個全局變量。要避免全局變量。php

2 – 使用===,而不是==css

==(或!=)操做符在須要的時候會自動執行類型轉換。===(或!==)操做不會執行任何轉換。它將比較值和類型,並且在速度上也被認爲優於==。html

1
2
3
4
5
6
7
8
[ 10 ] === 10    // is false
[ 10 ]  == 10    // is true
'10' == 10     // is true
'10' === 10    // is false
  []   == 0     // is true
  [] ===  0     // is false
  '' == false   // is true but true == "a" is false
  '' ===   false // is false

3 – 使用閉包實現私有變量(譯者添加)前端

1
2
3
4
5
6
7
8
9
10
11
12
function Person(name, age) {
     this .getName = function () { return name; };
     this .setName = function (newName) { name = newName; };
     this .getAge = function () { return age; };
     this .setAge = function (newAge) { age = newAge; };
 
     //未在構造函數中初始化的屬性
     var occupation;
     this .getOccupation = function () { return occupation; };
     this .setOccupation = function (newOcc) { occupation =
                          newOcc; };
}

4 – 在語句結尾處使用分號html5

在語句結尾處使用分號是一個很好的實踐。若是你忘記寫了你也不會被警告,由於多數狀況下JavaScript解釋器會幫你加上分號。java

5 – 建立對象的構造函數web

1
2
3
4
5
6
function Person(firstName, lastName){
     this .firstName =  firstName;
     this .lastName = lastName;
}
 
var Saad = new Person( "Saad" , "Mousliki" );

6 – 當心使用typeof、instanceof和constructorchrome

1
2
3
4
var arr = [ "a" , "b" , "c" ];
typeof arr;   // return "object"
arr  instanceof Array // true
arr.constructor();  //[]

7 – 建立一個自調用函數(Self-calling Funtion)數組

這個常常被稱爲自調用匿名函數(Self-Invoked Anonymous Function)或者即時調用函數表達式(IIFE-Immediately Invoked Function Expression)。這是一個在建立後當即自動執行的函數,一般以下:

1
2
3
4
5
6
7
( function (){
     // some private code that will be executed automatically
})();
( function (a,b){
     var result = a+b;
     return result;
})( 10 , 20 )

8- 從數組中獲取一個隨機項

1
2
3
var items = [ 12 , 548 , 'a' , 2 , 5478 , 'foo' , 8852 , , 'Doe' , 2145 , 119 ];
 
var  randomItem = items[Math.floor(Math.random() * items.length)];

9 – 在特定範圍內獲取一個隨機數

這個代碼片斷在你想要生成測試數據的時候很是有用,好比一個在最小最大值之間的一個隨機薪水值。

1
var x = Math.floor(Math.random() * (max - min + 1 )) + min;

10 – 在0和設定的最大值之間生成一個數字數組

1
2
3
var numbersArray = [] , max = 100 ;
 
for ( var i= 1 ; numbersArray.push(i++) < max;);  // numbers = [0,1,2,3 ... 100]

11 – 生成一個隨機的數字字母字符串

1
2
3
4
5
function generateRandomAlphaNum(len) {
     var rdmstring = "" ;
     for ( ; rdmString.length &lt; len; rdmString  += Math.random().toString( 36 ).substr( 2 ));
     return  rdmString.substr( 0 , len);
}

【譯者注:特地查了一下Math.random()生成0到1之間的隨機數,number.toString(36)是將這個數字轉換成36進制(0-9,a-z),最後substr去掉前面的「0.」字符串】

12 – 打亂一個數字數組

1
2
3
var numbers = [ 5 , 458 , 120 , - 215 , 228 , 400 , 122205 , - 85411 ];
numbers = numbers.sort( function (){ return Math.random() - 0.5 });
/* the array numbers will be equal for example to [120, 5, 228, -215, 400, 458, -85411, 122205]  */

13 – String的trim函數

在Java、C#、PHP和不少其餘語言中都有一個經典的 trim 函數,用來去除字符串中的空格符,而在JavaScript中並無,因此咱們須要在String對象上加上這個函數。

1
String .prototype.trim = function (){ return this .replace(/^\s+|\s+$/g, "" );};

【譯者注:去掉字符串的先後空格,不包括字符串內部空格】

14 – 附加(append)一個數組到另外一個數組上

1
2
3
4
5
var array1 = [ 12 , "foo" , {name: "Joe" } , - 2458 ];
 
var array2 = [ "Doe" , 555 , 100 ];
Array .prototype.push.apply(array1, array2);
/* array1 will be equal to  [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */

【譯者注:其實concat能夠直接實現兩個數組的鏈接,可是它的返回值是一個新的數組。這裏是直接改變array1】

15 – 將arguments對象轉換成一個數組

1
var argArray = Array .prototype.slice.call(arguments);

【譯者注:arguments對象是一個類數組對象,但不是一個真正的數組

16 – 驗證參數是不是數字(number)

1
2
3
function isNumber(n){
     return ! isNaN ( parseFloat (n)) && isFinite (n);
}

17 – 驗證參數是不是數組

1
2
3
function isArray(obj){
     return Object .prototype.toString.call(obj) === '[object Array]' ;
}

注意:若是toString()方法被重寫了(overridden),你使用這個技巧就不能獲得想要的結果了。或者你可使用:

1
Array .isArray(obj); // 這是一個新的array的方法

若是你不在使用多重frames的狀況下,你還可使用 instanceof 方法。但若是你有多個上下文,你就會獲得錯誤的結果。

1
2
3
4
5
6
7
8
9
var myFrame = document.createElement( 'iframe' );
document.body.appendChild(myFrame);
 
var myArray = window.frames[window.frames.length- 1 ]. Array ;
var arr = new myArray(a,b, 10 ); // [a,b,10]
 
// instanceof will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array ; // false

【譯者注:關於如何判斷數組網上有很多討論,你們能夠google一下。這篇就寫的挺詳細的。】

18 – 獲取一個數字數組中的最大值或最小值

1
2
3
var  numbers = [ 5 , 458 , 120 , - 215 , 228 , 400 , 122205 , - 85411 ];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);

【譯者注:這裏使用了Function.prototype.apply方法傳遞參數的技巧】

19 – 清空一個數組

1
2
var myArray = [ 12 , 222 , 1000 ];
myArray.length = 0 ; // myArray will be equal to [].

20 – 不要使用 delete 來刪除一個數組中的項。

使用 splice 而不要使用 delete 來刪除數組中的某個項。使用 delete 只是用 undefined 來替換掉原有的項,並非真正的從數組中刪除。

不要使用這種方式:

1
2
3
4
5
var items = [ 12 , 548 , 'a' , 2 , 5478 , 'foo' , 8852 , , 'Doe' , 2154 , 119 ];
items.length; // return 11
delete items[ 3 ]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

而使用:

1
2
3
4
5
var items = [ 12 , 548 , 'a' , 2 , 5478 , 'foo' , 8852 , , 'Doe' , 2154 , 119 ];
items.length; // return 11
items.splice( 3 , 1 ) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154,       119]   */

delete 方法應該被用來刪除一個對象的某個屬性。

21 – 使用 length 來截短一個數組

跟上面的清空數組的方式相似,咱們使用 length 屬性來截短一個數組。

1
2
var myArray = [ 12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4 ; // myArray will be equal to [12 , 222 , 1000 , 124].

此外,若是你將一個數組的 length 設置成一個比如今大的值,那麼這個數組的長度就會被改變,會增長新的 undefined 的項補上。 數組的 length 不是一個只讀屬性。

1
2
myArray.length = 10 ; // the new array length is 10
myArray[myArray.length - 1 ] ; // undefined

22 – 使用邏輯 AND/OR (更多)作條件判斷

1
2
3
var foo = 10 ;
foo == 10 && doSomething(); // 等價於 if (foo == 10) doSomething();
foo == 5 || doSomething(); // 等價於 if (foo != 5) doSomething();

邏輯 AND 還能夠被使用來爲函數參數設置默認值

1
2
3
function doSomething(arg1){
     Arg1 = arg1 || 10 ; // 若是arg1沒有被設置的話,Arg1將被默認設成10
}

23 – 使用 map() 方法來遍歷一個數組裏的項

1
2
3
4
var squares = [ 1 , 2 , 3 , 4 ].map( function (val) {
     return val * val;
});
// squares will be equal to [1, 4, 9, 16]

24 – 四捨五入一個數字,保留N位小數

var num =2.443242342;
1.num = num.toFixed(4);  // num will be equal to 2.4432
2.num=Math.round(num * 10000) /10000

  

25 – 浮點數問題

1
2
3
0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994

爲何會這樣? 0.1+0.2等於0.30000000000000004。你要知道,全部的JavaScript數字在內部都是以64位二進制表示的浮點數,符合IEEE 754標準。更多的介紹,能夠閱讀這篇博文。你可使用 toFixed() 和 toPrecision() 方法解決這個問題。

26 – 使用for-in遍歷一個對象內部屬性(更多的時候注意檢查屬性

下面的代碼片斷可以避免在遍歷一個對象屬性的時候訪問原型的屬性

1
2
3
4
5
for ( var name in object) {
     if (object.hasOwnProperty(name)) {
         // do something with name
     }
}
注:向Array的原型中添加擴展方法後,當使用for-in循環數組時,這個擴展方法也會被循環出來。 譬如: 
Array.prototype.contain = function (obj) {
    return this.indexOf(obj) !== -1;
}
var arr = [1, 23, 45];
for (var i in arr) {
    console.log(i);
}
//輸出:1 23 45  function (obj) { return this.indexOf(obj) !== -1; }

解決這個問題:

for (var i in arr) {
    if (arr.hasOwnProperty(i))
        console.log(i);
}

27 – 逗號操做符

1
2
3
4
var a = 0 ;
var b = ( a++, 99 );
console.log(a);  // a will be equal to 1
console.log(b);  // b is equal to 99

28 – 緩存須要計算和查詢(calculation or querying)的變量

對於jQuery選擇器,咱們最好緩存這些DOM元素。

1
2
3
4
var navright = document.querySelector( '#right' );
var navleft = document.querySelector( '#left' );
var navup = document.querySelector( '#up' );
var navdown = document.querySelector( '#down' );

29 – 在調用 isFinite()以前驗證參數

1
2
3
4
5
6
7
isFinite ( 0 / 0 ) ; // false
isFinite ( "foo" ); // false
isFinite ( "10" ); // true
isFinite ( 10 );   // true
isFinite (undifined);  // false
isFinite ();   // false
isFinite ( null );  // true  !!!

30 – 避免數組中的負數索引(negative indexes)

1
2
3
var numbersArray = [ 1 , 2 , 3 , 4 , 5 ];
var from = numbersArray.indexOf( "foo" ) ;  // from is equal to -1
numbersArray.splice(from, 2 );    // will return [5]

確保調用 indexOf 時的參數不是負數。

31 – 基於JSON的序列化和反序列化(serialization and deserialization)

1
2
3
4
5
var person = {name : 'Saad' , age : 26 , department : {ID : 15 , name : "R&D" } };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}"   */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object  */

32 – 避免使用 eval() 和 Function 構造函數

使用 eval 和 Function 構造函數是很是昂貴的操做,由於每次他們都會調用腳本引擎將源代碼轉換成可執行代碼。

1
2
var func1 = new Function(functionCode);
var func2 = eval(functionCode);

33 – 避免使用 with()

使用 with() 會插入一個全局變量。所以,同名的變量會被覆蓋值而引發沒必要要的麻煩。

34 – 避免使用 for-in 來遍歷一個數組

避免使用這樣的方式:

1
2
3
4
var sum = 0 ;
for ( var i in arrayNumbers) {
     sum += arrayNumbers[i];
}

更好的方式是:

1
2
3
4
var sum = 0 ;
for ( var i = 0 , len = arrayNumbers.length; i < len; i++) {
     sum += arrayNumbers[i];
}

附加的好處是,i 和 len 兩個變量的取值都只執行了一次,會比下面的方式更高效:

1
for ( var i = 0 ; i < arrayNumbers.length; i++)

爲何?由於arrayNumbers.length每次循環的時候都會被計算。

35 – 在調用 setTimeout() 和 setInterval() 的時候傳入函數,而不是字符串。

若是你將字符串傳遞給 setTimeout() 或者 setInterval(),這個字符串將被如使用 eval 同樣被解析,這個是很是耗時的。
不要使用:

1
2
setInterval( 'doSomethingPeriodically()' , 1000 );
setTimeOut( 'doSomethingAfterFiveSeconds()' , 5000 )

而用:

1
2
setInterval(doSomethingPeriodically, 1000 );
setTimeOut(doSomethingAfterFiveSeconds, 5000 );

36 – 使用 switch/case 語句,而不是一長串的 if/else

在判斷狀況大於2種的時候,使用 switch/case 更高效,並且更優雅(更易於組織代碼)。但在判斷的狀況超過10種的時候不要使用 switch/case。
【譯者注:查了一下文獻,你們能夠看一下這篇介紹

37 – 在判斷數值範圍時使用 switch/case

在下面的這種狀況,使用 switch/case 判斷數值範圍的時候是合理的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getCategory(age) {
     var category = "" ;
     switch ( true ) {
         case isNaN (age):
             category = "not an age" ;
             break ;
         case (age >= 50 ):
             category = "Old" ;
             break ;
         case (age <= 20 ):
             category = "Baby" ;
             break ;
         default :
             category = "Young" ;
             break ;
     };
     return category;
}
getCategory( 5 );  // will return "Baby"

【譯者注:通常對於數值範圍的判斷,用 if/else 會比較合適。 switch/case 更適合對肯定數值的判斷】

38 – 爲建立的對象指定prototype對象

寫一個函數來建立一個以指定參數做爲prototype的對象是有可能:

1
2
3
4
5
6
function clone(object) {
     function OneShotConstructor(){};
     OneShotConstructor.prototype= object;
     return new OneShotConstructor();
}
clone( Array ).prototype ;  // []

39 – 一個HTML轉義函數

1
2
3
4
5
6
function escapeHTML(text) {
     var replacements= { "<" : "<" , ">" : ">" , "&" : "&" , "\"" : "" "};
     return text.replace(/[<>&"]/g, function (character) {
         return replacements[character];
     });
}

40 – 避免在循環內部使用 try-catch-finally

在運行時,每次當 catch 從句被執行的時候,被捕獲的異常對象會賦值給一個變量,而在 try-catch-finally 結構中,每次都會新建這個變量。

避免這樣的寫法:

1
2
3
4
5
6
7
8
9
var object = [ 'foo' , 'bar' ], i;
for (i = 0 , len = object.length; i <len; i++) {
     try {
         // do something that throws an exception
     }
     catch (e) {
         // handle exception
     }
}

而使用:

1
2
3
4
5
6
7
8
9
var object = [ 'foo' , 'bar' ], i;
try {
     for (i = 0 , len = object.length; i <len; i++) {
         // do something that throws an exception
     }
}
catch (e) {
     // handle exception
}

41 – 爲 XMLHttpRequests 設置超時。

在一個XHR請求佔用很長時間後(好比因爲網絡問題),你可能須要停止此次請求,那麼你能夠對XHR調用配套使用 setTimeout()。

1
2
3
4
5
6
7
8
9
10
11
12
13
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
     if ( this .readyState == 4 ) {
         clearTimeout(timeout);
         // do something with response data
     }
}
var timeout = setTimeout( function () {
     xhr.abort(); // call error callback
}, 60 * 1000 /* timeout after a minute */ );
xhr.open( 'GET' , url, true ); 
 
xhr.send();

此外,通常你應該徹底避免同步的Ajax請求。

42 – 處理WebSocket超時

一般,在一個WebSocket鏈接建立以後,若是你沒有活動的話,服務器會在30秒以後斷開(time out)你的鏈接。防火牆也會在一段時間不活動以後斷開鏈接。

爲了防止超時的問題,你可能須要間歇性地向服務器端發送空消息。要這樣作的話,你能夠在你的代碼裏添加下面的兩個函數:一個用來保持鏈接,另外一個用來取消鏈接的保持。經過這個技巧,你能夠控制超時的問題。

使用一個 timerID:

1
2
3
4
5
6
7
8
9
10
11
12
13
var timerID = 0 ;
function keepAlive() {
     var timeout = 15000 ;
     if (webSocket.readyState == webSocket.OPEN) {
         webSocket.send( '' );
     }
     timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
     if (timerId) {
         cancelTimeout(timerId);
     }
}

keepAlive()方法應該被添加在webSOcket鏈接的 onOpen() 方法的最後,而 cancelKeepAlive() 添加在 onClose() 方法的最後。

43 – 牢記,原始運算符始終比函數調用要高效。使用VanillaJS

舉例來講,不使用:

1
2
var min = Math.min(a,b);
A.push(v);

而用:

1
2
var min = a < b ? a b;
A[A.length] = v;

44 – 編碼的時候不要忘記使用代碼整潔工具。在上線以前使用JSLint和代碼壓縮工具(minification)(好比JSMin)。《省時利器:代碼美化與格式化工具

45 – JavaScript是難以想象的。最好的JavaScript學習資源

46 – Javascript的String.format()

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}
調用:"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
if (!String.format) {
  String.format = function(format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function(match, number) {
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}
調用:String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

47 – 動態加載外部JavaScript或CSS文件  

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}
 
loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

48 – 動態加載外部JavaScript並監聽文件是否加載完成

function loadScript(url, callback){
    var script = document.createElement ("script")
    script.type = "text/javascript";
    if (script.readyState){ //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function(){
            callback();
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

49 – 變量和函數聲明被提早

先來看一段代碼:

var name = "Baggins";
(function () {
    // Outputs: "Original name was undefined"
    console.log("Original name was " + name);

    var name = "Underhill";
    // Outputs: "New name is Underhill"
    console.log("New name is " + name);
})();

對javascript不瞭解,可能會產生2個疑問:

1.爲何第一次輸出的不是"Baggins"

2.即便第一次不輸出"Baggins"爲何沒有報錯?

首先解釋第二個疑問:爲何在未定義變量name的狀況下,沒有報錯。

這實際上是 JavaScript 解析器搞的鬼,解析器將當前做用域內聲明的全部變量和函數都會放到做用域的開始處,可是,只有變量的聲明被提早到做用域的開始處了,而賦值操做被保留在原處。上述代碼對於解析器來講實際上是以下這個樣子滴:

var name = "Baggins";
(function () {
    var name;  //注意:name 變量被提早了!

    // Outputs: "Original name was undefined"
    console.log("Original name was " + name);

    name = "Underhill";
    // Outputs: "New name is Underhill"
    console.log("New name is " + name);
})();

理解了這個,第一個也就好理解了。這個和做用域鏈有關係。在執行的時候,首先會在函數內部的執行環境中尋找name,若是沒有尋找到,就會一直往上(能夠理解爲父級)尋找。沒有找到就會報錯。變量如此,函數亦然。具體可見JavaScript 中對變量和函數聲明的「提早(hoist)

基於此變量的聲明最好是寫在變量做用域的最前端

50 – 爲何是===而不是==

null==undefined這個之因此成立,是由於undefined實際上也是null。而typeof null===undefined是不成立的是因爲此時比較的是他們的類型。更詳細的解釋能夠參看undefined與null的區別

51 – 關於if(statement)判斷

if(statement){ //其實是執行Boolean(statement)轉型操做
    console.log(true);
}else{
    console.log(false);
}

這個等同於

 if (undefined != statement && null != statement && "" != statement && 0!=statement){
       console.log("true");
 }else{
       console.log("false");
 }

基於此,定義變量初始化值的時候,若是基本類型是string,咱們賦值空字符串,若是基本類型是number咱們賦值爲0,若是是引用類型,咱們能夠直接定義爲null。

 52 – 關於原型和原型鏈

什麼是原型?

原型是一個對象,其餘對象能夠經過它實現屬性繼承。

什麼是原型鏈?

每一個對象和原型都有一個原型(注:原型也是一個對象),對象的原型指向對象的父,而父的原型又指向父的父,咱們把這種經過原型層層鏈接起來的關係撐爲原型鏈。這條鏈的末端通常老是默認的對象原型。

一小段代碼加深理解:

 

var Point = function (x, y) {
    this.x = x;
    this.y = y;
}
Point.prototype.add = function (otherPoint) {
    this.x += otherPoint.x;
    this.y += otherPoint.y;
}
var p1 = new Point(3, 4);
var p2 = new Point(8, 6);
p1.add(p2);

 

一個簡圖來闡釋一下:

(即:p1.__proto__[Point.prototype].__proto__[Object.prototype].__proto__==null)

(這就是原型鏈)

深刻查看原型原型繼承

 53 – new運算符

 概要:new運算符的做用是建立一個對象實例。這個對象能夠是用戶自定義的,也能夠是帶構造函數的一些系統自帶的對象。

 

function Person(name,age) {
      this.name=name;
      this.age=age;      
}
Person.prototype={
      getName:function(){
           return this.name;
      },
      getage:function(){
           return this.age;
      }
}
var coco=new Person('coco',12);
console.log(coco.getName());

 

new操做符會讓構造函數產生以下變化:

1.建立一個新的對象;

2.將構造函數的做用域賦值給新對象(所以this對象就指向了這個新的對象)

3.執行構造函數中的代碼(爲這個新對象添加屬性);

4.返回新對象

要理解這4點請看上面例子對應的等同變體:

function Person(name,age) {
      this.name=name;
      this.age=age;      
}
Person.prototype={
      getName:function(){
           return this.name;
      },
      getage:function(){
           return this.age;
      }
}
var coco={};
coco.__proto__=Person.prototype
Person.call(coco,'coco',12);

54 – call/apply改變函數中this的指向

// 定義一個全局函數
function foo() {
    if (this === window) {
        console.log("this is window.");
    }
}

// 函數foo也是對象,因此能夠定義foo的屬性boo爲一個函數
foo.boo = function () {
    if (this === foo) {
        console.log("this is foo.");
    } else if (this === window) {
        console.log("this is window.");
    }
};
// 等價於window.foo();
foo();  // this is window.

// 能夠看到函數中this的指向調用函數的對象
foo.boo();  // this is foo.

// 使用apply改變函數中this的指向
foo.boo.apply(window);  // this is window.

55 – input的type類型的修改問題

要實現一個相似登錄框提示用戶輸入的功能,咱們會想到placeholder,可是咱們知道placeholder是html5的新屬性,因此在不一樣的瀏覽器下的兼容性是有問題的。因而想到直接修改文本框的類型,當嘗試使用jQuery來修改元素的屬性的時候,很不幸,在chrome的控制檯下會直接輸出error信息:"Uncaught type property can't be changed"當嘗試使用原生的javascript來修改:input.setAttribute("type","password");在ie8及下版本是徹底不支持的。由於這個時候type是隻讀的。另外提供一個實現placeholder功能的比較好的js插件,見這裏

56 – 關於外掛文件和將腳本寫在$(document).ready()中的誤區

咱們經常被告知,js要和html文檔分離,而且內置的腳本最好要寫在$(document).ready()而不是$(window).load()中。但事實上,這個並非萬能法則。咱們外掛的js文檔要加載,須要一次服務器請求,雖然如今的瀏覽器支持的請求數成倍增長,然而若是成千上萬的人一塊兒訪問網站,請求給服務器形成的壓力也是可想而知的,請求的時間若是再算在內的話,將腳本直接包含在網頁底部或許能節省一些時間。另外若是頁面文檔很是大,加載起來很是慢(特別是有大量外鏈的時候),這個時候你若是將控件的事放在$(document).ready()中,就極可能當你想觸發按鈕的事件的時候,文檔還沒有加載完成。所以這個時候建議將這部分js腳本放在對應文檔的底部(直接放在文檔後面也多是有問題的,若是事件代碼包含還沒有加載好的文檔節點就會有錯)。

 

 

總結

我知道還有不少其餘的技巧,竅門和最佳實踐,因此若是你有其餘想要添加或者對我分享的這些有反饋或者糾正,請在評論中指出。

本文大部分在自:伯樂在線 和我的總結

相關文章
相關標籤/搜索