js類(繼承)(一)

//call()
//調用一個對象的一個方法,以另外一個對象替換當前對象。
//call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
//參數
//thisObj
//可選項。將被用做當前對象的對象。
//arg1, arg2, , argN
//可選項。將被傳遞方法參數序列。
//說明
//call 方法能夠用來代替另外一個對象調用一個方法。call 方法可將一個函數的對象上下文從初始的上下文改變爲由 thisObj 指定的新對象。
//若是沒有提供 thisObj 參數,那麼 Global 對象被用做 thisObj。
 
 
function  Person(name){    //父類
     this .name=name;
     this .SayHello= function (){alert( "Hello, I'm " + this .name);};
}
function  Employee(name,salary){   //子類
     Person.call( this ,name);       //將this傳給父構造函數
     this .salary=salary;
     this .ShowMeTheMoney= function (){alert( this .name+ " $" + this .salary);};
}
 
var  BillGates= new  Person( "Bill Gates" );
var  SteveJobs= new  Employee( "Steve Jobs" ,1234);
 
BillGates.SayHello();  //顯示:I'm Bill Gates
SteveJobs.SayHello();  //顯示:I'm Steve Jobs
SteveJobs.ShowMeTheMoney();  //顯示:Steve Jobs $1234
 
alert(BillGates.constructor == Person);   //true
alert(SteveJobs.constructor == Employee); //true

直接定義prototype彷佛更有extends 的意韻javascript

function  Person(name){    //父類
     this .name=name;
     this .SayHello= function (){alert( "Hello, I'm " + this .name);};
}
function  Employee(salary){   //子類
     this .salary=salary;
     this .ShowMeTheMoney= function (){alert( this .name+ " $" + this .salary);};
}
Employee.prototype= new  Person( "Steve Jobs" );
var  SteveJobs= new  Employee(1234);
 
SteveJobs.SayHello();  //顯示:I'm Steve Jobs
SteveJobs.ShowMeTheMoney();  //顯示:Steve Jobs $1234

 

 

文章出自:http://www.cnblogs.com/frostbelt/archive/2012/04/01/2428014.htmlhtml

相關文章
相關標籤/搜索