JavaScript語法總結 - Notes

1. 各java一樣採用Unicode編碼.

2. 可省略分號, 如

return

true

<=>

return;

true;

而非return true;

這個感覺不爽, 容易出錯而不知.

3. 大小寫敏感.

數據類型:

4. null, 空值, 表示的是無值; undefined, 未定義, 表示未賦值或不存在對象屬性.

對於==來說兩者並無區別, ===和typeof區分兩者.

5. 數組和對象都是數值的集合, 對象中的每個數值都有一個名字, 而數組中的每個數值都有一個數字, 即下標.

基本數據類型的包裝對象Number, Bealean, String, 和java真像. 必要時自動轉換, 所以兩者使用並無多大差別.

5. 隱式聲明的變量總是被創建爲全局變量, 不管在哪裏.

6. 沒有塊級作用域

函數中聲明的所有變量, 在整個函數中有定義, 但在初始化語句之前並沒被初始化. 如:

var scope = “global”;

function f()

{

alert(scope); // 顯示 “undefined”

var scope = “local”; // 初始化, 但整個函數中有定義

alert(scope); // 顯示 “local”

}

f();

7. 基本數據類型: 數值, 布爾值, null, undefined

引用類型: 對象, 數組, 函數

字符串: 複製對字符串的引用, 其他表現又與基本類型相似, 比較時使用的是值, 這點與Java不同. 值不可變.

8. Javascript解釋器開始運行時, 首先創建一個全局對象, 而聲明的全局變量實際上是它的屬性. 局部變量是調用對象(call object)的屬性. call object生命期較短.

所以變量和對象的屬性實質上是一樣的, 這樣隨意的添加屬性就和定義變量一樣, 沒啥奇怪的了.

每個框架或窗口都有各自的執行環境, 各自全局對象, 但可以互相引用.

9. in運算符:

判斷是否左邊是右邊的屬性名.

var point = {x:1, y:1};

var a = “x” in point; // true

var b = “tostring” in point; // true, 繼承屬性

10. delete

var o = {x:1, y:1};

delete o.x;

刪除屬性, 變量, 數組元素.

注意的是當delete的不是屬性, 數組元素或變量, 也返回true.

var聲明的變量不能刪除, 某些核心屬性和客戶端屬性也不能.

v1.1前只是設爲null.

11. void運算符

捨棄運算數的值, 返回undefined.

<a href=”javascript:void window.open();” >Open New Window</a>

這個的作用是由於open()返回值被轉爲undefined, 所以僅僅彈出一個窗口, 而原頁面並不跳轉, 如果改爲如下, 而頁面將跳轉到空白頁面.

<a href=”window.open();” >Open New Window</a>

12. .運算符左邊必須是一個標誌符.

13. for/in

for (variable in object)

statement

14. with

暫時修改作用鏈

with (object)

statement


對象


15. 對象創建:

var o = new Object();

o.x = 1.1;

o.xx = true;

var now = new Date();

var pattern = new RegExp(“//sjava//s”, “i”);

可以以關聯數組的方式引用, 實際上數據也是一種特殊的對象.

o[“x”], o[“xx”]

16. 對象直接量

var point = {x:2.3, y:-1.2};

17. 嵌套

var retangle = {upperLeft:{x:2, y:2}, lowRight:{x:4, y:4}};



函數

18. 函數是一個真正的數據類型, 可以被存儲在變量, 數組和對象中, 可以作爲參數. 函數實際上爲一個特殊的對象.

19. 函數在定義它的作用域中執行.

// This function returns a function each time it is called // The scope in which the function is defined differs for each call

function makefunc(x) {

return function( ) { return x; }

}

// Call makefunc( ) several times, and save the results in an array:

var a = [makefunc(0), makefunc(1), makefunc(2)];

// Now call these functions and display their values.

// Although the body of each function is the same, the scope is

// different, and each call returns a different value:

alert(a[0]( )); // Displays 0

alert(a[1]( )); // Displays 1

alert(a[2]( )); // Displays 2

19. 函數定義

1).

function square(x)

{

return x*x;

}

2).

函數直接量定義

function [函數名可選](參數){函數體}

var square = function(x) {return x*x;}

3).

lambda

var square = new Function(“x”, “return x*x;”); // x是參數, return x*x;是函數體.

20.對象構造函數:

// 無返回值, 否則new的結果就是返回值, 而不是該對象了.

function Rectangle(w, h)

{

this.width = w;

this.height = h;

}

var rect = new Rectangle(2, 4);


21. 屬性的繼承只發生在讀屬性值時, 寫屬性不會發生. 因爲JS中函數(方法)都是數據類型, 所以把這些方法和常量放在原型(prototype)中, 使這部分空間被多個對象共享, 這樣便可以大大節省內存.

New Circle(); // 先new是爲了兼容JS1.1. 大多數版本中, 每個函數都自動有一個空的原型對象, 而JS1.1只有在該函數首次被用作構造函數時, 纔會創建一個原型.

Rectangle.prototype.pi = 3.14159;

function cal_area() { return this.w * this.h; }

Rectangle.prototype.calAera = cal_area;



22. 因爲函數也是對象, 所以類屬性就是函數屬性, 是構造函數的屬性.

類方法


23. 函數實際參數:

arguments對象, 可下標, 屬性有length, callee.

function f(x, y, z)

{

if (arguments.length > 3)

{

alert(arguments[3]);

}

arguments[0] = 1;

alert(x); // 顯示1, 因爲x與arguments[0]引用同一變量

}

function (x)

{

if (x <= 1)

{

return 1;

}

return x * arguments.callee(x-1):

}


24. Function.length, 函數定義中的參數個數

function check(args)

{

if (args.length != args.callee.length) // 實際個數 != 定義個數

{

throw new Error(“Haha”);

}

}

function f(x, y, z)

{

check(arguments);

}

25. 自定義函數屬性, 可實現像java, c++中的函數靜態變量.

f.counter = 0;

function f()

{

return f.counter++;

}

26. 每個函數都有apply()和call()

f.call(ob, 1, 2);

<=>

ob.m = f;

ob.m(1, 2);

delete ob.m;

<=>

f.apply(ob, [1, 2]); // apply區別是參數作爲數組元數傳進.

var biggest = Math.max.apply(null, [1, 2, 3, 4]);

Javascript1.2實現了apply()方法, Javascript1.5實現了call()方法.

27. Function()

1).

允許在運行時動態地創建和編譯Javascript代碼. 而函數直接量是程序結構的靜態部分, 就和function語句一樣.

2).

每次調用Function()時都會解析函數體並且創建一個新的函數對象. 這在循環中效率會很低, 而函數直接量和嵌套函數都只編譯一次.

3).

使用構造函數Function()創建的函數不使用詞法作用域, 它們總是被當作頂級函數來編譯.

var y = “global”;

function constructFunction()

{

var y = “local”;

return new Function(“return y”); // 不捕捉局部作用域

}

alert(constructFunction()()); // 顯示 “global”

28. Javascript中的繼承

以原型(prototype)爲基礎的繼承

Function Hello(a)

{

this.x = a;

}


Function MyHello(b)

{

this.y = b;

}


MyHello.prototype = new Hello(0);

MyHello.prototype.constructor = MyHello; // Javascript1.1中這個屬性只讀, 不能這樣定義

這樣, 在MyHello中查詢屬性時, 首先查詢的是這個對象本身, 其次是MyHello.prototype, 再其次是Hello.prototype, 最後是Object.prototype. 構造函數的原型默認就是Object, 除非重新定義.



29. 關聯數組的好處

object.property ? object[“property”]

前者屬性是標誌符, 後者是字符串, 後者就能實現靈活動態的效果, 如果反射.

var addr = “”;

for (i=0; i<4; i++)

{

addr += customer[“address”+i] + ‘/n’;

}


var value = 0;

for (stock in portfolio)

{

Value += portfolio[stock] * getValues(stock);

}

30. for/in循環遍歷所有對象的所有可能的屬性. 實際上for/in有不能枚舉出來的屬性, 如一些標記成了只讀的, 永久的或者不可枚舉的屬性, e.g. Object.valueof

for/in可以用於數組.



31. Object的屬性

所有對象繼承Object.

32. constructor屬性

if ((typeof o == “Object”) && (o.construcotr == Date)) // 判斷o是否爲Date.


33. toString(), toLocaleString() 和 valueof()

默認的toString()只提供”[object Object]”信息. 有時想要調用這個函數以實現”type of “的功能, 這樣必須明確指明調用它:

Object.prototype.toString.apply(o);

如下:

function Typeof(x)

{

var t = typeof x;

if (t != “Object”)

{

return t;

}

var c = O bject.prototype.toString.apply(x);

c = c.substring(8, c.length-1); //去掉”[object” 和 “]”

return c;

}


默認toLocaleString()與toString()一樣, 不過很多類會定義它, 包括內部類, e.g. Array, Date, Number, etc.


默認valueof()不進行任何轉換. 注意有的環境valueof()的優先級比toString()高, 所以有時最好還是強制調用valueof().


34. hasOwnProperty() 判斷是否是非繼承的屬性, 不是和無這個屬性都返回false.


35. isPrototypeOf() 判斷調用對象是否爲參數的原型對象, 從函數名就知.



數組

36. 數組創建:

1).

var a = new Array();

a[0] = 1.2;

a[1] = “java”;

a[2] = true;

a[3] = {x:1, y:3};

2).

var a = new Array(1.2, “java”, true);

3).

var a = new Array(10); //10個未定義元素

4).

數組直接量

var a = [1.2, “Java”, true];

var matrx = [[1, 2, 3], [2, 3, 4], [5, 6, 7]];

var base = 100;

var table = [base, base+1, base+2];

var sparseArray = [1,,,,100]; // 其中有三個未定義元素

37. 數組下標爲0—2^32-1的整數, 其他值將被轉換成字符串看待, 即關聯數組看待.

38. JS中數組是稀疏的(sparse), 這樣如下只需爲兩個元素分配內存:

a[0] = 1;

a[10000] = “haha”;


var c = new Circle(1, 2, 3);

c[0] = “hello”;

上面只是定義了一個名爲”0”的對象屬性, 而非數組, 數組必須用Array()或數組直接量定義, 儘管數組是一個特殊的對象. 不過數組有一些特性.

39. 所有數組含屬性length. 像上上面那樣, a.length的值爲10001, 而非2, 雖然只分配了兩個元素的內存.


40. JS中無多維數組, 和JAVA一樣, 可以嵌套. 但可以使用多維數組的表達多式, 即多箇中括號.


41. 數組有很多方法:

join(), reverse(), sort(), concat(), slice(), splice(); push(), pop(); unshift(), shift(), toString(), toSource().



Javascript正則表達式

42. 是perl5正則表達式的子集.

var pattern = /s$/; // 正則表達式直接量

var pattern2 = new RegExp(“s$”);

43. 特殊字符

^ $ . * + ? = ! : | / / ( ) [ ] { }

44. 語法

Alphanumeric character

Itself

/0

The NUL character (/u0000)

/t

Tab (/u0009)

/n

Newline (/u000A)

/v

Vertical tab (/u000B)

/f

Form feed (/u000C)

/r

Carriage return (/u000D)

/xnn

The Latin character specified by the hexadecimal number nn; for example, /x0A is the same as /n

/uxxxx

The Unicode character specified by the hexadecimal number xxxx; for example, /u0009 is the same as /t

/cX

The control character ^X; for example, /cJ is equivalent to the newline character /n

[...]

Any one character between the brackets.

[^...]

Any one character not between the brackets.

.

Any character except newline or another Unicode line terminator.

/w

Any ASCII word character. Equivalent to [a-zA-Z0-9_].

/W

Any character that is not an ASCII word character. Equivalent to [^a-zA-Z0-9_].

/s

Any Unicode whitespace character.

/S

Any character that is not Unicode whitespace. Note that /w and /S are not the same thing.

/d

Any ASCII digit. Equivalent to [0-9].

/D

Any character other than an ASCII digit. Equivalent to [^0-9].

[/b]

A literal backspace (special case).

{n,m}

Match the previous item at least n times but no more than m times.

{n,}

Match the previous item n or more times.

{n}

Match exactly n occurrences of the previous item.

?

Match zero or one occurrences of the previous item. That is, the previous item is optional. Equivalent to {0,1}.

+

Match one or more occurrences of the previous item. Equivalent to {1,}.

*

Match zero or more occurrences of the previous item. Equivalent to {0,}.

|

Alternation. Match either the subexpressions to the left or the subexpression to the right.

(...)

Grouping. Group items into a single unit that can be used with *, +, ?, |, and so on. Also remember the characters that match this group for use with later references.

(?:...)

Grouping only. Group items into a single unit, but do not remember the characters that match this group.

/num

Match the same characters that were matched when group number n was first matched. Groups are subexpressions within (possibly nested) parentheses. Group numbers are assigned by counting left parentheses from left to right. Groups formed with (?: are not numbered.

^

Match the beginning of the string and, in multiline searches, the beginning of a line.

$

Match the end of the string and, in multiline searches, the end of a line.

/b

Match a word boundary. That is, match the position between a /w character and a /W character or between a /w character and the beginning or end of a string. (Note, however, that [/b] matches backspace.)

/B

Match a position that is not a word boundary.

(?=p)

A positive look-ahead assertion. Require that the following characters match the pattern p, but do not include those characters in the match.

(?!p)

A negative look-ahead assertion. Require that the following characters do not match the pattern p.


45. 匹配是貪婪的, 但可以用?實現非貪婪的重複, 只需在重複字符後加?即可.

??, +?, *?, {2, 4}?

對於字符串abcd12345:

//d{2, 4}/ // 匹配2到4 個數字, 匹配結果爲1234

//d{2, 4}?/ //結果爲12

對於字符串 aaab

/a*b/ //匹配aaab

/a*?b/ //也匹配aaab, 而非b, 因爲正則表達式模式匹配是在尋找字符串中第一個可能匹配的位置, 如果還要找下一個匹配, 則會在上一個匹配結束的後一個字符開始繼續匹配.

46. 選擇, 分組和引用

選擇項是從左到右考慮, 直到發現匹配項. 如果左邊的選擇項匹配, 就忽略右邊的選擇項, 即使它產生更好的匹配.

對於字符串ab,

/a|ab/ //只匹配a

47. 括號的作用: 把單獨的項目組合成子表達式, 以便|, *, +, ?等使用, 如/java(script)?/; 另一作用是定義子模式, /['”][^'”]*/1/.

48. 對正則表達式中前一子表達式的引用所指的並不是那個子表達式的模式, 而是與那個模式相匹配的文本. 另外, /num中的num是左括號的位置, 如/(java(script)?)/s(hehe)/的/2是指(script).


49. 標誌

i

Perform case-insensitive matching.

g

Perform a global match. That is, find all matches rather than stopping after the first match.

m

Multiline mode. ^ matches beginning of line or beginning of string, and $ matches end of line or end of string.


50. 自動類型轉換

只要把非空對象用在布爾環境中, 它就會被轉換成true.

new Boolean(false) // 內部值是false, 但該對象將被轉換成true.

51. 在大多數情況下, Js會先嚐試調用對象的valueof方法進行轉換, 或無valueof, 則再調用tostring進行轉換. 但有一種例外, 當運算符 “+” 作用於Date對象時, 首先調用tostring進行轉換.

52. 強制轉換

var x_as_string = x + “”;

var x_as_number = x – 0;

var x_as_boolean = !!x;

var string_value = String(number);


var n = 17;

binary_string = n.tostring(2); // 10001

octal_string = “0” + n.tostring(8); // 021

hex_string = “0x” + n.tostring(16); // 0x11

 
發佈了35 篇原創文章 · 獲贊 0 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章