詳解JS物件導向編程,js物件導向編程
因為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(){}//繼承personStudent.prototype = new Person("iwen",1);//修改因繼承導致的constructor變化Student.prototype.constructor = Student;var s = new Student();alert(s.name);//iwenalert(s instanceof Person);//trues.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(){}//繼承personStudent.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);//trues.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程式設計有所協助。
您可能感興趣的文章:
- JAVASCRIPT THIS詳解 物件導向
- JS 拼圖遊戲 物件導向,注釋完整。
- javascript 物件導向編程基礎 多態
- javascript 物件導向全新理練之資料的封裝
- JavaScript 物件導向之命名空間
- JS物件導向編程之對象流量分析
- Javascript 物件導向(一)(共有方法,私人方法,特權方法)
- JS左右無縫滾動(一般方法+物件導向方法)
- javascript物件導向入門基礎詳細介紹