一、基本的類的使用
方法一:
function sth(a) // 構造函數 
{ 
 this.a = a; 
 this.fun = output; // 成員函數 
} 
function output(a, b, c) 
{ 
 document.write(this.a); 
} 
//調用
var s = new sth(250); 
s.fun(1, 2, 3); 
ouput(1, 2, 3); //如果output在sth之前就是錯的
方法二:
function sth(a) 
{   
 this.a = a; 
 this.output = function() 
 { 
  document.write(this.a); 
 } 
} 
var s = new sth(2); 
s.output(); // 輸出2 
二、繼承
方法一:
function A(x) 
{ 
 this.x = x; 
} 
function B(x, y) 
{ 
 // 方法1 
 /* 
 this.construct = A; 
 this.construct(x); 
 delete this.construct; 
 */  
 // 方法2 
 //A.call(this, x); 
 // 方法3 
 A.apply(this, new Array(x)); // 亦可A.apply(this, arguments), 不過arguments參數順序一定要對 
 this.y = y; 
 this.print = function() 
 { 
  document.write("x = ", x, 
         ", y = ", y); 
 } 
} 
var b = new B(1, 2); 
b.print();
alert(B instanceof A); // 輸出false
優點:可以實現多繼承(多調用call就好) 
缺點: 
? 必須以構造函數方式使用 
? 使用instanceof運算符運算此類繼承結果為false
方法二:
function A() 
{ 
} 
A.prototype.x = 1; 
function B() 
{ 
} 
B.prototype = new A(); // 不能帶參數! 
B.prototype.y = 2;  
B.prototype.print = function() 
{ 
 document.write(this.x, ", ", this.y, "<br>"); 
} 
var b = new B(); 
b.print(); 
document.write(b instanceof A); // 輸出true
缺點: 
? 不能實現多繼承 
? 構造函數不帶參數Tips
通常使用混合模式,兩者一起用
function A(x) 
{ 
 this.x = x; 
} 
A.prototype.printx = function()  // 寫到A類里面this.printx = function....也是可以的,下同
{ 
 document.write(this.x, "<br>"); 
} 
function B(x, y) 
{ 
 A.call(this, x); 
 this.y = y; 
} 
B.prototype = new A(); // 不能帶參數!  
B.prototype.printxy = function() 
{ 
 document.write(this.x, ", ", this.y, "<br>"); 
} 
var b = new B(1, 2); 
b.printx();  // 輸出1 
b.printxy(); // 輸出1, 2 
document.write(b instanceof A); // 輸出true
三、類似靜態成員函數的使用
function sth(a) 
{   
 this.a = a; 
} 
sth.fun = function(s) 
{ 
 document.write(s.a); 
} 
var s = new sth(2); 
sth.fun(s); // 輸出2
四、對象的釋放
var obj = new Object; // obj是引用
obj = null; // 取消引用,會自動進行垃圾回收;如果需要根本釋放此對象,要將它的所有引用都賦值為null
五、函數對象
var v = new Function("arg1", "arg2", "document.write(arg1 + arg2);"); // 定義一個函數對象,參數分別是arg1,arg2 
v(1, 2); // 將會輸出3
六、回調函數
function callback(func, arg) 
{ 
 func(arg); 
} 
function fun(arg) 
{ 
 document.write(arg); 
}
//callback(func, "sb"); // 這種做法不行 
var func = new Function("arg", "fun(arg);"); 
// 當然也可以把func(arg)換成具體的執行代碼,   
// 但是函數代碼龐大了就最好這樣做了 
callback(func, "sb");
七、函數的重載
function fun() 
{ 
 switch (arguments.length) 
 { 
 case 1: 
  document.write(arguments[0]); 
  break; 
 case 2: 
  document.write(arguments[0] + arguments[1]); 
  break; 
 default: 
  document.write("ERROR!"); 
  break; 
 } 
} 
fun(1); 
fun(1, 2);
八、利用函數閉包實現有“靜態變量”的函數
function fun() 
{ 
 var v = 1; 
 function fun2() 
 { 
  ++v; 
  document.write(v); 
  document.write("<br>"); 
  return v; 
 } 
 return fun2; 
} 
var func = fun(); 
func(); // 輸出2 
func(); // 輸出3 
func(); // 輸出4