亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解JS面向?qū)ο缶幊?/h1>
 更新時間:2016年01月24日 10:25:30   投稿:lijiao  
這篇文章主要為大家介紹了js面向?qū)ο缶幊?,感興趣的小伙伴們可以參考一下

因為JavaScript是基于原型(prototype)的,沒有類的概念(ES6有了,這個暫且不談),我們能接觸到的都是對象,真正做到了一切皆為對象

所以我們再說對象就有些模糊了,很多同學(xué)會搞混類型的對象和對象本身這個概念,我們在接下來的術(shù)語中不提對象,我們使用和Java類似的方式,方便理解

方式一

類(函數(shù)模擬)

function Person(name,id){
 //實例變量可以被繼承
 this.name = name;
 //私有變量無法被繼承
 var id = id;
 //私有函數(shù)無法被繼承
 function speak(){
  alert("person1");
 }
}
//靜態(tài)變量,無法被繼承
Person.age = 18;
//公有函數(shù)可以被繼承
Person.prototype.say = function(){
 alert("person2");
}

繼承,并調(diào)用父類方法

function Person(name,id){
 //實例變量可以被繼承
 this.name = name;
 //私有變量無法被繼承
 var id = id;
 //私有函數(shù)無法被繼承
 function speak(){
  alert("person1");
 }
}
//靜態(tài)變量,無法被繼承
Person.age = 18;
//公有靜態(tài)成員可被繼承
Person.prototype.sex = "男";
//公有靜態(tài)函數(shù)可以被繼承
Person.prototype.say = function(){
 alert("person2");
}
//創(chuàng)建子類
function Student(){
}
//繼承person
Student.prototype = new Person("iwen",1);
//修改因繼承導(dǎo)致的constructor變化
Student.prototype.constructor = Student;
var s = new Student();
alert(s.name);//iwen
alert(s instanceof Person);//true
s.say();//person2

繼承,復(fù)寫父類方法且實現(xiàn)super()

function Person(name,id){
 //實例變量可以被繼承
 this.name = name;
 //私有變量無法被繼承
 var id = id;
 //私有函數(shù)無法被繼承
 function speak(){
  alert("person1");
 }
}
//靜態(tài)變量,無法被繼承
Person.age = 18;
//公有靜態(tài)成員可被繼承
Person.prototype.sex = "男";
//公有靜態(tài)函數(shù)可以被繼承
Person.prototype.say = function(){
 alert("person2");
}
//創(chuàng)建子類
function Student(){
}
//繼承person
Student.prototype = new Person("iwen",1);
//修改因繼承導(dǎo)致的constructor變化
Student.prototype.constructor = Student;
//保存父類的引用
var superPerson = Student.prototype.say;
//復(fù)寫父類的方法
Student.prototype.say = function(){
 //調(diào)用父類的方法
 superPerson.call(this);
 alert("Student");
}
//創(chuàng)建實例測試
var s = new Student();
alert(s instanceof Person);//true
s.say();//person2 student

繼承的封裝函數(shù)

function extend(Child, Parent) {

    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
  }

uber意思是為子對象設(shè)一個uber屬性,這個屬性直接指向父對象的prototype屬性。(uber是一個德語詞,意思是”向上”、”上一層”。)這等于在子對象上打開一條通道,可以直接調(diào)用父對象的方法。這一行放在這里,只是為了實現(xiàn)繼承的完備性,純屬備用性質(zhì)。

方式二

相當(dāng)于拷貝,通過定義的_this對象來承載想要被繼承的對象,這樣的話通過傳遞_this就可以實現(xiàn)繼承,比上面那種好理解些

//創(chuàng)建父類
function Person(name,id){
 //創(chuàng)建一個對象來承載父類所有公有東西
 //也就是說_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;
 //復(fù)寫父類的方法
 _this.say = function(){
  //執(zhí)行父類的say
  superPerson.call(_this);
  alert("Student");
 }
 return _this;
}
var s = new Student();
s.say();

希望對大家學(xué)習(xí)javascript程序設(shè)計有所幫助。

相關(guān)文章

最新評論