iT邦幫忙

0

Prototype

在Constructor的章節中我們使用建立實體的方式

function Person(name, age){
    this.name = name
    this.age = age
}
let c = new Person("Dennis", 22)
console.log(c) //Person { name: 'Dennis', age: 22 }

但今天我想建立一個function可以自我介紹Constructor的方法是

function Person(name, age){
    this.name = name
    this.age = age
    this.SayHi = function() { 
        console.log(`$Hello I'm ${this.name} my age is ${this.age} `)
    }
}
let c = new Person("Dennis", 22)
c.SayHi() //$Hello I'm Dennis my age is 22 

還有一個就是今天的重點Prototype

當我們使用new建立一個物件的時候SayHi這個function會一直重複並且占用記憶體,但明明都一樣何必多創造
所以我們把他抽取出來透過prototype指向SayHi這個function

function Person(name, age){
    this.name = name
    this.age = age
}

Person.prototype.SayHi = function(){
    console.log(`Hello I'm ${this.name} my age is ${this.age}`)
}

let c = new Person("Dennis", 22) 
c.SayHi() //Hello I'm Dennis my age is 22

https://ithelp.ithome.com.tw/upload/images/20210521/201304198kaNXpawL7.png
在這裡就透過prototype去指向SayHi function了

JavaScript prototype無所不在

let num = 23
let Num = new Number(23)

console.log(typeof(num)) //number
console.log(typeof(Num)) //object

https://ithelp.ithome.com.tw/upload/images/20210521/20130419axyw67DSeC.png

上面的圖完整示範了在JavaScript不論你定義number、string等等,都會透過Prototype去繼承相關的method


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言