HackMD
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    2
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Prototype / Constructor If you haven't done so already, read the [:zap: Objects](https://hackmd.io/s/Skr0aRtSV) byte. Take a look at the following scenario: ```js const honda = { wheels: 4, doors: 5, drive () { console.log('vroom') } } const citroen = { wheels: 4, doors: 3, drive () { console.log('vroom') } } ``` We have 2 cars. Both have the exact same methods and properties but differing property values. In this scenario, there are downsides to creating objects in this way: * We have to keep repeating ourselves each time we make a car. * If we spell a property name wrong on say the `citroen` then our application might not work correctly when we come to use the object. * The `drive` method will be exactly the same for each car, yet we're storing it multiple times in memory. ## :car: A different approach to building a car We know that both `citroen` and `peugoet` are cars, so what if there was a way we could create a scaffold for what a car is, and then just create `citroen` and `peugoet` from that scaffold? Fortunately, the Prototype / Constructor pattern in JavaScript allows us to do this. Let's take a look: ```js function Car (wheels, doors) { this.wheels = wheels this.doors = doors } ``` This is referred to as a _constructor_. When called with the `new` keyword, a new object is created in memory, which the `this` keyword is bound to (so we can add properties to the object as above). Let's see how we can use this constructor to make a `Car`: ```js const peugoet = new Car(4, 5) const citroen = new Car(4, 3) ``` When we use the `new` keyword, we create a new _instance_ of `Car`. If you `console.log` out `peugoet` and `citroen` you get: ![Properties](https://s3.eu-west-2.amazonaws.com/mcrcodes/course/prototype/properties.png) If you're observant, you may have noticed I've excluded the `drive` method. This is because I _could_ add a method like so: ```js function Car (wheels, doors) { this.wheels = wheels this.doors = doors this.drive = function () { console.log('vroom') } } ``` **But** there is a more efficient way. Introducing the _prototype_: ```js function Car (wheels, doors) { this.wheels = wheels this.doors = doors } Car.prototype = { drive () { console.log('vroom') } } ``` If we create a new `peugoet` and a new `citroen` now and we `console.log` them out we get the same again: ![Properties](https://s3.eu-west-2.amazonaws.com/mcrcodes/course/prototype/properties.png) You can see that we have the exact same properties as before. As before, it's still possible to access these properties via dot notation. But...but where is the `drive` method!? If you click down into the object you will see a `__proto__` key. If you click down into this, you should see the `drive` method: ![Prototype](https://s3.eu-west-2.amazonaws.com/mcrcodes/course/prototype/prototype.png) What's happening here is that we have 2 object instances that have their own properties (`wheels` and `doors`) but they inherit their methods from their parent's (`Car`) prototype. This inheriting of methods from a parent object is referred to as _inheritance_. You can still call `peugoet.drive()` - JavaScript will look to the prototype of the object (`__proto__`) to find the method if it can't find it on the object itself. In other words: * A _constructor_ allows us to create a scaffold for what the properties on a new object should look like. These properties belong to the object instance. * A _prototype_ allows us to specify methods which are to be shared across new object instances. These methods belong to the object instance's parent (in this scenario `Car`). ## Private properties/methods There are some properties and methods that we want to tell other developers and users it's not okay to access directly (because we want to control what is and isn't available outside of the object's prototype). For example, imagine if the NHS made patient data from its Trusts available for researchers to use. Perhaps we have an object called `Trust`: ```js function Trust (name, location, medicalRecords) { this.name = name this.location = location this.medicalRecords = medicalRecords } ``` Now imagine a new Trust has opened in a city :hospital: , and 3 patients from another Trust have been transferred across. We might instantiate this Trust like so: ```js const uhcw = new Trust('UHCW', 'Coventry', [ { patient: 'Murray', conditions: ['Anxiety'] }, { patient: 'Lucia', conditions: ['Diabetes', 'Fibromyalgia'] }, { patient: 'Tiger', conditions: ['Liver Disease'] } ]) ``` If we as the NHS want to share data with researchers, the last thing we want to allow is for somebody to do: ```js uhcw.medicalRecords ``` As this will provide them not only with the medical conditions, but with identifying information for each patient. To work around this, we can name our `medicalRecords` property with an underscore `_`. This will signify that this property shouldn't be accessed from outside the object: ```js function Trust (name, location, medicalRecords) { this.name = name this.location = location this._medicalRecords = medicalRecords } ``` Now we can make a method on the prototype so that researchers can get only the information they need from each Trust: ```js Trust.prototype = { getMedicalRecords () { return this._medicalRecords.map(medicalRecord => medicalRecord.conditions) } } ``` Researchers can now call `uhcw.getMedicalRecords()` without patient data being compromised. ### A couple of things to note Private doesn't exist properly in JavaScript. It is still possible to call `uhcw._medicalRecords`. We use `_` to signify to other developers that they shouldn't be accessing properties (and methods) directly in this way. In other languages, the concept of _private_ is enforced more strictly, so it's something to be aware of (especially as you may end up working in a different language). It's also worth mentioning that you can use the same `_` convention to create private methods on a prototype (that would be called by the prototype's other _public_ methods). ## A more practical example of Prototype / Constructor Let's say we have a cash machine. Cash machines generally exist in number (there are _apparently_ 3.5 million of them worldwide), and aside from things like where they are located and which bank they belong to, they all have the same functionality - they allow us to withdraw money and to view our statements. So what changes from one cash machine to another? * `bank` * `location` These will be our properties. We can therefore go on to make our constructor: ```js function CashMachine (bank, location) { this.bank = bank this.location = location } ``` What about withdrawals? It's safe to say that one cash machine won't have the exact same withdrawals as another cash machine. Withdrawals is also plural, which insinuates we might want to consider an array. Let's add one more property to keep track of these. We'll make it a _private_ property so we can limit the user of `CashMachine` to only be able to view their own withdrawals: ```js function CashMachine (bank, location) { this.bank = bank this.location = location this._withdrawals = [] } ``` Now, what doesn't change from one cash machine to another? Our functionality: * `withdraw` * `viewStatement` This functionality will sit on the `CashMachine` prototype, for all new `CashMachine` instances to access: ```js CashMachine.prototype = { withdraw (cardNumber, amount) { this._withdrawals.push({ cardNumber: cardNumber, amount: amount }) }, viewStatement (cardNumber) { return this._withdrawals.filter(withdrawal => withdrawal.cardNumber === cardNumber) } } ``` It's assumed that cash machines will be used by multiple users, so a `cardNumber` field is added to all withdrawals to uniquely identify each user. Here we use `this` to access the `_withdrawals` property on an object's instance, which is an array. In `viewStatement` we [filter](arrays/filter.md) these results so the user of the `CashMachine` can only view their transactions. ## Additonal Reading The Prototype / Constructor concept is a difficult one to grasp at first, but keep going at it and it will become much clearer. Here are some additional reading materials that may help (would recommend reading in order): * [Create objects in JavaScript](https://hackernoon.com/create-objects-in-javascript-10924cfa9fc7) * [Prototypes in JavaScript](https://hackernoon.com/prototypes-in-javascript-5bba2990e04b) * [JavaScript Constructors and Prototypes](http://tobyho.com/2010/11/22/javascript-constructors-and/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully