实现继承的方式
/*** 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承*/function Parent1(){this.name = "parent1";}Parent1.prototype.say = function(){};function Child1(){//將父構(gòu)造函數(shù)的this指向子構(gòu)造函數(shù)的實(shí)例上Parent1.call(this);//applythis.type = "child1";}console.log(new Child1);/*** 借助原型鏈實(shí)現(xiàn)繼承*/function Parent2(){this.name = 'parent2';this.play = [1,2,3];}function Child2(){this.type = 'child2';}Child2.prototype = new Parent2();console.log(new Child2);var s1 = new Child2();var s2 = new Child2();console.log(s1.play,s2.play);s1.play.push(4);/*** 組合方式* 缺點(diǎn)民:實(shí)例化兩次父類*/function Parent3(){this.name = "parent3";this.play = [1,2,3];}function Child3(){Parent3.call(this);this.type = 'child3';}Child3.prototype = new Parent3();var s3 = new Child3();var s4 = new Child3();s3.play.push(4);console.log(s3.play, s4.play);/*** 組合繼承的優(yōu)化1*/function Parent4(){this.name = "parent4";this.play = [1,2,3];}function Child4(){Parent4.call(this);this.type = 'child4';}Child4.prototype = Parent4.prototype;var s5 = new Child4();var s6 = new Child4();console.log(s5, s6);console.log(s5 instanceof Child4,s5 instanceof Parent4);//構(gòu)造函數(shù)是一個(gè),無法判斷實(shí)例是父類創(chuàng)建還是子類創(chuàng)建
console.log(s5.constructor);/*** 組合繼承優(yōu)化2*/function Parent5(){this.name = "parent5";this.play = [1,2,3];}function Child5(){Parent5.call(this);this.type = 'child5';}//創(chuàng)建中間對象Child5.prototype = Object.create(Parent5.prototype);Child5.prototype.constructor = Child5;var s7 = new Child5();console.log(s7 instanceof Child5, s7 instanceof Parent5);console.log(s7.constructor); //模擬new func就是一個(gè)構(gòu)造函數(shù)var new2 = function(func){//第一步,創(chuàng)建一個(gè)空對象,空對象關(guān)聯(lián)構(gòu)造函數(shù)的原型對象var o = Object.create(func.prototype);//第二步,執(zhí)行構(gòu)造函數(shù),k表示返回結(jié)果var k = func.call(o);//第三步,判斷構(gòu)造函數(shù)的動(dòng)行結(jié)果是不是對象類型if(typeof k === 'object'){return k;}else{return o;}}
轉(zhuǎn)載于:https://www.cnblogs.com/huyanluanyu/p/10106248.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
- 上一篇: 赏金猎人,不祥之刃,光辉女郎这三人哪个好
- 下一篇: 铁血护国之青年朱德剧情介绍