Day15-ProtoType

前言

在经过前面几天的章节之後,我们对於如何使用JavaScript与相关的知识有一些概念了。

今天我们要来更深入了解JavaScript的运作原理Prototype(原型)与prototype chain(原型链)

  • ProtoType
  • proto

Constructor function

JavaScript有别於其他程序语言 如:Java、C#等等,本身并没有类别的概念。

在JavaScript中我们会利用建构函数去建立设计模型

function User(name, age, sex) {
  this.name = name,
  this.age = age,
  this.sex = sex,
  this.sayHi = function() {
    console.log(this.name + 'Hi');
  }
}

并且我们会使用new 这个关键字,建立我们的实体。

const Ian = new User('Ian', 22, 'male')

打印出来看看

console.log(Ian);

https://ithelp.ithome.com.tw/upload/images/20210821/20130419qIYjaaze7A.png

可以看到被建立为一个实体物件了!!!

测试一下,是否正常

Ian.sayHi()
Jessica.sayHi()

ProtoType

由建构函数new 出一个实体代表我们会建立一个专属的记忆体位置。

但是若有100个实体,那岂不是创立了100个sayHi method造成效能浪费吗???

先来测试是否指向不同的位置

console.log(Ian.sayHi === Jessica.sayHi) //false

Ok,结果是没错的

那我们要怎麽改进呢???

先把Ian的实体打印出来看看

console.log(Ian)

https://ithelp.ithome.com.tw/upload/images/20210821/20130419guqHwySFYR.png

可以看到Ian其实是去取用User的prototype

那我们换个想法,把User的参考prototype增加一个不就可以共用了吗!?

User.prototype.sayHi = function() {
  console.log(this.name + ' Hi');
}

更改过後的程序码

function User(name, age, sex) {
  this.name = name,
  this.age = age,
  this.sex = sex
}

User.prototype.sayHi = function() {
  console.log(this.name + ' Hi');
}
const Ian = new User('Ian', 22, 'male')
const Jessica = new User('Jessica', 22, 'female')

Ian.sayHi() //Ian Hi

果然跟我们所想的一样,可以这样扩充我们的属性。

打印看看Ian跟Jessica的sayHi function是否相同记忆体

console.log(Ian.sayHi === Jessica.sayHi); //true

太棒了我们成功了解prototype了!!!

proto

那你说JavaScript是怎麽帮我们指向过去到所参考的ProtoType???

答案就是__proto__

https://ithelp.ithome.com.tw/upload/images/20210821/20130419wRNPVhTdPe.png

把Ian.__proto__打印出来看看是否是利用__proto__连结的

console.log(Ian.__proto__); 

https://ithelp.ithome.com.tw/upload/images/20210821/20130419koBjxHSBKu.png

没错拉!!! Ian.__proto__确实指向到了User的ProtoType

最後我们用Array来做最後测试

建立一个Array实体

const arrayTest = new Array(1,2,3)
console.log(arrayTest.filter((item) => item > 1))

我们有办法不宣告任何方法即可使用filter等等method,即是透过prototype。

https://ithelp.ithome.com.tw/upload/images/20210821/20130419FI1mRUpBjw.png


<<:  Day 05 CSS <基础选择器>

>>:  Day01: 01 - 前置准备: 版面设计、安装、开启专案

【Day2】Information Security Overview

随着新的科技环境变化, 资讯安全也会变得更多面向。 根据NIST(美国国家标准暨技术研究院)定义的电...

阻止B-1B轰炸机前进的不是敌人是一台平板

转自新闻原文 美国空军派遣的B-1B轰炸机在驻紮挪威期间,其中一架轰炸机因发动机吸入平板电脑,导致两...

[Day 9]Request

首先利用function index来测试Request功能,在终端机上打php artisan r...

资安这条路 28 - [作业系统] Windows、Linux

Windows安全 帐号密码安全 目前主机上有哪些帐号 net user Windows 使用者帐号...

Spring Framework X Kotlin Day 5 JPA

GitHub Repo https://github.com/b2etw/Spring-Kotlin...