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

http://img2.58codes.com/2024/201304198kaNXpawL7.png
在这里就透过prototype去指向SayHi function了

JavaScript prototype无所不在

let num = 23let Num = new Number(23)console.log(typeof(num)) //numberconsole.log(typeof(Num)) //object

http://img2.58codes.com/2024/20130419axyw67DSeC.png

上面的图完整示範了在JavaScript不论你定义number、string等等,都会透过Prototype去继承相关的method


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章