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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

面象对象

發布時間:2024/4/14 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 面象对象 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • ?類的聲明:

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

  • es6中class的聲明:

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

// 實例化 console.log(new Animal(),new Animal2())復制代碼
  • 借助構造函數實現繼承

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

借助原型鏈實現繼承

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共用一原型對象,一個改變另外一個也會改變。復制代碼

組合方式實現繼承

// 寫面向對象繼承的通用方式 // (缺點)父類執行兩次。 function Parent3() {this.name = 'parent3';this.play = [1, 2, 3] }function Child3() {Parent3.call(this); // Parent3執行第一次this.type = 'child3' }Child3.prototype = new Parent3(); // Parent3執行第二次 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。復制代碼

組合方式實現繼承(優化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。復制代碼

組合方式實現繼承(優化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復制代碼


轉載于:https://juejin.im/post/5bd69a4de51d457a9b6c853c

總結

以上是生活随笔為你收集整理的面象对象的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。