Skip to content

Instantly share code, notes, and snippets.

@anibal21
Created April 20, 2022 05:06

Revisions

  1. anibal21 created this gist Apr 20, 2022.
    61 changes: 61 additions & 0 deletions JS_CALLvsAPPLYvsBind.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    /**
    * Explanation with an interview example from real life
    * Call invokes the function and allows you to pass in arguments one by one.
    * Apply invokes the function and allows you to pass in arguments as an array.
    * Bind returns a new function, allowing you to pass in a this array and any number of arguments.
    **/

    // Call - Example
    const callSomeone = (name, callback) => {
    const innerMessage= {
    message: name + ' Hi Mothafucka'
    }
    callback.call(innerMessage)
    }

    function telephone (name) {

    return callSomeone(name, function () {
    console.log(this.message)
    })

    }

    telephone('Anibal')

    // Apply - Example
    const callSomeone = (name, callback) => {
    const innerMessage= {
    message: name + ' Hi Mothafucka'
    }
    callback.apply(innerMessage)
    }

    function telephone (name) {

    return callSomeone(name, function () {
    console.log(this.message)
    })

    }

    telephone('Anibal')

    // Bind - example
    const callSomeone = (name, callback) => {

    const innerMessage= {
    message: name + ' Hi Mothafucka'
    }
    callback.bind(innerMessage)()
    }

    function telephone (name) {

    return callSomeone(name, function () {
    console.log(this.message)
    })

    }

    telephone('Anibal')