日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

面象对象

發(fā)布時(shí)間:2024/4/14 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 面象对象 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
  • ?類的聲明:

function Animal () { this.name = 'name';}復(fù)制代碼

  • es6中class的聲明:

class Animal2 {constructor() {this.name = 'name'} }復(fù)制代碼

// 實(shí)例化 console.log(new Animal(),new Animal2())復(fù)制代碼
  • 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承

function Parent1() {this.name = 'parent1' }Parent1.prototype.say = function () {console.log('say') }function Child1() {Parent1.call(this) // apply 改變函數(shù)上下文(this)this.type = 'child1' }console.log(new Child1) // console.log(new Child1().say()) // say方法如果在構(gòu)造函數(shù)里面可以實(shí)現(xiàn)繼承,但如果父類的原型對(duì)象上還有方法,子類是拿不到方法。復(fù)制代碼

借助原型鏈實(shí)現(xiàn)繼承

function Parent2() {this.name = 'Parent2';this.play = [1, 2, 3, 4] }function Child2() {this.type = 'child2'; }Child2.prototype = new Parent2() console.log(new Child2()) console.log(new Child2().__proto__) var s1 = new Child2() var s2 = new Child2()s1.play.push(5) console.log(s1.play, s2.play) // s1,s2共用一原型對(duì)象,一個(gè)改變另外一個(gè)也會(huì)改變。復(fù)制代碼

組合方式實(shí)現(xiàn)繼承

// 寫面向?qū)ο罄^承的通用方式 // (缺點(diǎn))父類執(zhí)行兩次。 function Parent3() {this.name = 'parent3';this.play = [1, 2, 3] }function Child3() {Parent3.call(this); // Parent3執(zhí)行第一次this.type = 'child3' }Child3.prototype = new Parent3(); // Parent3執(zhí)行第二次 var s3 = new Child3() var s4 = new Child3() s4.play.push(4) console.log(s3.play, s4.play) console.log(s3.constructor) console.log(s4.constructor) // s3s4的constructor指向是父類Parent3。復(fù)制代碼

組合方式實(shí)現(xiàn)繼承(優(yōu)化1)

function Parent4() {this.name = 'parent4';this.play = [1, 2, 3, 4]; }function Child4() {Parent4.call(this);this.type = 'child4'; }Child4.prototype = Parent4.prototype; // 引用類型 var s5 = new Child4(); var s6 = new Child4(); s5.play.push(5); console.log(s5, s6); console.log(s5 instanceof Child4, s5 instanceof Parent4) // true,true console.log(s5.constructor) console.log(s6.constructor) // s5s6的constructor指向都是父類Parent4。復(fù)制代碼

組合方式實(shí)現(xiàn)繼承(優(yōu)化2)

function Parent5() {this.name = 'parent5';this.play = [1, 2, 3, 4]; }function Child5() {Parent5.call(this);this.type = 'child5'; }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) // s7的constructor指向Child5復(fù)制代碼


轉(zhuǎn)載于:https://juejin.im/post/5bd69a4de51d457a9b6c853c

總結(jié)

以上是生活随笔為你收集整理的面象对象的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。