//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 的意韻
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
注:這里的Person.call(this.name)就像super(this.name)一樣,哥在java里都不太用,不過了解一下總是好的
