因為JavaScript是基於原型(prototype)的,沒有類的概念(ES6有了,這個暫且不談),我們能接觸到的都是對象,真正做到了一切皆為對象
所以我們再說對象就有些模糊了,很多同學會搞混類型的對象和對象本身這個概念,我們在接下來的術語中不提對象,我們使用和Java類似的方式,方便理解
方式一
類(函數模擬)
function Person(name,id){
//實例變量可以被繼承
this.name = name;
//私有變量無法被繼承
var id = id;
//私有函數無法被繼承
function speak(){
alert("person1");
}
}
//靜態變量,無法被繼承
Person.age = 18;
//公有函數可以被繼承
Person.prototype.say = function(){
alert("person2");
}
繼承,並調用父類方法
function Person(name,id){
//實例變量可以被繼承
this.name = name;
//私有變量無法被繼承
var id = id;
//私有函數無法被繼承
function speak(){
alert("person1");
}
}
//靜態變量,無法被繼承
Person.age = 18;
//公有靜態成員可被繼承
Person.prototype.sex = "男";
//公有靜態函數可以被繼承
Person.prototype.say = function(){
alert("person2");
}
//創建子類
function Student(){
}
//繼承person
Student.prototype = new Person("iwen",1);
//修改因繼承導致的constructor變化
Student.prototype.constructor = Student;
var s = new Student();
alert(s.name);//iwen
alert(s instanceof Person);//true
s.say();//person2
繼承,復寫父類方法且實現super()
function Person(name,id){
//實例變量可以被繼承
this.name = name;
//私有變量無法被繼承
var id = id;
//私有函數無法被繼承
function speak(){
alert("person1");
}
}
//靜態變量,無法被繼承
Person.age = 18;
//公有靜態成員可被繼承
Person.prototype.sex = "男";
//公有靜態函數可以被繼承
Person.prototype.say = function(){
alert("person2");
}
//創建子類
function Student(){
}
//繼承person
Student.prototype = new Person("iwen",1);
//修改因繼承導致的constructor變化
Student.prototype.constructor = Student;
//保存父類的引用
var superPerson = Student.prototype.say;
//復寫父類的方法
Student.prototype.say = function(){
//調用父類的方法
superPerson.call(this);
alert("Student");
}
//創建實例測試
var s = new Student();
alert(s instanceof Person);//true
s.say();//person2 student
繼承的封裝函數
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
uber意思是為子對象設一個uber屬性,這個屬性直接指向父對象的prototype屬性。(uber是一個德語詞,意思是”向上”、”上一層”。)這等於在子對象上打開一條通道,可以直接調用父對象的方法。這一行放在這裡,只是為了實現繼承的完備性,純屬備用性質。
方式二
相當於拷貝,通過定義的_this對象來承載想要被繼承的對象,這樣的話通過傳遞_this就可以實現繼承,比上面那種好理解些
//創建父類
function Person(name,id){
//創建一個對象來承載父類所有公有東西
//也就是說_this承載的對象才會被傳遞給子類
var _this = {};
_this.name = name;
//這樣的是不會傳遞下去的
this.id = id;
//承載方法
_this.say = function(){
alert("Person");
}
//返回_this對象
return _this;
}
//子類
function Student(){
//獲取person的_this對象,從而模仿繼承
var _this = Person("iwne",1);
//保存父類的_this引用
var superPerson = _this.say;
//復寫父類的方法
_this.say = function(){
//執行父類的say
superPerson.call(_this);
alert("Student");
}
return _this;
}
var s = new Student();
s.say();
希望對大家學習javascript程序設計有所幫助。