国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

初探JavaScript 面向對象(推薦)

2024-05-06 16:39:27
字體:
來源:轉載
供稿:網友

類的聲明

1. 構造函數

function Animal() { this.name = 'name'}// 實例化new Animal()

2. ES6 class

class Animal { constructor() {  this.name = 'name' }}// 實例化new Animal()

類的繼承

1. 借助構造函數實現繼承

原理:改變子類運行時的 this 指向,但是父類原型鏈上的屬性并沒有被繼承,是不完全的繼承

function Parent() { this.name = 'Parent'}Parent.prototype.say = function(){ console.log('hello')}function Child() { Parent.call(this) this.type = 'Child'}console.log(new Parent())console.log(new Child())

2. 借助原型鏈實現繼承

原理:原型鏈,但是在一個子類實例中改變了父類中的屬性,其他實例中的該屬性也會改變子,也是不完全的繼承

function Parent() { this.name = 'Parent' this.arr = [1, 2, 3]}Parent.prototype.say = function(){ console.log('hello')}function Child() { this.type = 'Child'}Child.prototype = new Parent()let s1 = new Child()let s2 = new Child()s1.arr.push(4)console.log(s1.arr, s2.arr)console.log(new Parent())console.log(new Child())console.log(new Child().say())

3. 構造函數 + 原型鏈

最佳實踐

// 父類function Parent() { this.name = 'Parent' this.arr = [1, 2, 3]}Parent.prototype.say = function(){ console.log('hello')}// 子類function Child() { Parent.call(this) this.type = 'Child'}// 避免父級的構造函數執行兩次,共用一個 constructor// 但是無法區分實例屬于哪個構造函數// Child.prototype = Parent.prototype// 改進:創建一個中間對象,再修改子類的 constructorChild.prototype = Object.create(Parent.prototype)Child.prototype.constructor = Child// 實例化let s1 = new Child()let s2 = new Child()let s3 = new Parent()s1.arr.push(4)console.log(s1.arr, s2.arr) // [1, 2, 3, 4] [1, 2, 3]console.log(s2.constructor) // Childconsole.log(s3.constructor) // Parentconsole.log(new Parent())console.log(new Child())console.log(new Child().say())

總結

以上所述是小編給大家介紹的JavaScript 面向對象(推薦)的相關知識,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 墨竹工卡县| 望谟县| 奇台县| 临海市| 吉木萨尔县| 布尔津县| 榕江县| 盐山县| 壤塘县| 宁蒗| 新干县| 昌吉市| 阿拉善左旗| 六盘水市| 江华| 郧西县| 乌海市| 永修县| 乌兰县| 绥滨县| 横峰县| 远安县| 安福县| 大连市| 甘肃省| 和平县| 原平市| 昭苏县| 庆安县| 洞口县| 娱乐| 建平县| 临颍县| 云梦县| 新野县| 宝鸡市| 长武县| 安乡县| 龙陵县| 寿光市| 沙田区|