js面向對象繼承
js的面向對象變成其實是基於對象的開發(js是沒有累的概念);
1:任何基於對象的變成都有三個特征,抽象封裝,繼承,多態。
1 抽象封裝:抽象指抽取對象的屬性和行為(方法),然後有機的結合在一起,這個過程叫做封裝,結果就是只對外提供接口(通過this創建共有屬性共有方法),而隱藏內部的實現(共有方法可以調用私有的方法)。
2 :繼承:子類實現擁有父類的屬性和方法的過程稱之為繼承;常用的繼承凡事如下兩種。
1:call或者apply
function F(x){
this.x=x
this.sayX=function(){
alert(this.x)
}
}
function Y(x){
F.call(this,x);
//F.apply(this,agruments);
}
var t=new Y(2);
alert(t.sayX())//2
註意??:call apply是無法調用
function F(x){
this.x=x
}
F.prototype.sayX=function(){
alert(this.x)
}
function Y(x){
F.call(this,x);
}
var t=new Y(2);
alert(t.sayX())//new_file.html?__hbt=1524886368955:91 Uncaught TypeError: t.sayX is not a function
2 原型鏈繼承
function Person(name, sex){
this.name=name;
this.sex=sex;
}
Person.prototype.showName=function(){
alert(this.name);
}
Person.prototype.showSex=function(){
alert(this.sex);
}
function worker(name,sex,job){
this.job=job;
Person.apply(this,arguments)//獲取公有的屬性
}
worker.prototype=new Person()
worker.prototype.sayJob=function(){
alert(this.job)
}
var n=new worker(‘xxw‘,‘nan‘,‘chenguxyuan‘);
console.log(n)
alert(n.showName())//xxw
alert(n.showSex())//nan
alert(n.sayJob())//chenguxyuan
3 多態
js 天然支持多態度
通過判斷參數argumrnts還有若數據類型,賦值什麽數據就是什麽數據
js面向對象繼承