js中的繼承有多少種方式?去某度搜一下,說幾種的都有,
看的頭暈眼花,仍是雲裏霧裏,因而就本身認真理一下,寫一篇按照本身的理解來進行的分類。javascript
JS實現繼承的核心技術點無非幾種:java
1: new 關鍵字 2: prototype 3: call、apply 4: Object.create() ES5 5: Object.assign() ES6 6: 拷貝(深拷貝、淺拷貝)
網上有說4,5,6種的,大可能是組合使用而後根據具體使用狀況分類, 也有阮一峯老師按照構造函數、非構造函數的分類(這個好理解些),
這些都各有各的道理,可是都是他們的分類,不是我本身理解的分類, 因此即便此次看懂了,下次不免會忘記,所以本身總結一下。app
1,構造函數式繼承,new函數
var func=function(name){ this.name=name }; var b=new func("b"); var c=new func("c"); b.name;//b c.name;//c
2,原型鏈式繼承,prototypethis
var func=function(des){ this.des=des; }; func.prototype.color="red"; var b=function(){ this.color=function(){ return "green" } return "orange" }; b.prototype=func.prototype;//私有的des沒法繼承 b()//orange new b().color()// green new b().color;// function(){return "green"} 私有覆蓋公有
3,call、applygoogle
/*父*/ function Parent(add,net,no,teacher) { this.add = add; this.net = net; this.no = no; this.teacher = teacher } /*子*/ function Child(name,age,sex,id) { this.name = name; this.sex = sex; this.age = age; this.id = id; Parent.call(this,"添加","www.google.com","1024","copy"); //這個時候的Parent中的this已經被Child所代替 } var child = new Child("都變了","18","男","2333"); child.add //添加
function Parent(add,net,no,teacher) { this.add = add; this.net = net; this.no = no; this.teacher = teacher } /*子類*/ function Child(name,age,sex,id) { this.name = name; this.sex = sex; this.age = age; this.id = id; Parent.apply(this,["添加","www.google.com","1024","copy"]); //這個時候的Parent中的this已經被Child所代替 } var child = new Child("都變了","18","男","2333"); child.add //添加
4,Object.create() ES5支持.net
var func=function(des){ this.des=des || "empty" }; func.prototype.getDes=function(){ return this.des } var b=function(){} b.prototype=Object.create(new func("哈哈哈")); //此處new func("哈哈哈") 用JSON對象替代可能會比較好理解,不過不修改也是有緣由的 new b("Dobie").getDes()// 哈哈哈
5: Object.assign() ES6支持prototype
var func=function(des){ this.des=des || "empty" }; func.prototype.getDes=function(){ return this.des } var b=function(){} b.prototype=Object.assign(new func("哈哈哈")); //此處new func("哈哈哈") 用JSON對象替代可能會比較好理解 new b("Dobie").getDes()// 哈哈哈
6: 拷貝(深拷貝、淺拷貝)code
這個去某度搜一下就能夠,暫時留坑,原理如標題名,就是循環複製一份出來, 區別是淺拷貝只拷貝引用(推薦瞭解 javascript 堆和棧,又是一個坑), 修改時會影響到父類,深拷貝則是徹底單獨開闢新的存儲地址,不會互相影響