在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
在这里就透过prototype去指向SayHi function了
JavaScript prototype无所不在
let num = 23let Num = new Number(23)console.log(typeof(num)) //numberconsole.log(typeof(Num)) //object
上面的图完整示範了在JavaScript不论你定义number、string等等,都会透过Prototype去继承相关的method