Skip to content

Instantly share code, notes, and snippets.

@marcinjahn
Last active August 17, 2020 19:11
Show Gist options
  • Save marcinjahn/20a4f258746d00c3cc5cb5dac25708aa to your computer and use it in GitHub Desktop.
Save marcinjahn/20a4f258746d00c3cc5cb5dac25708aa to your computer and use it in GitHub Desktop.

Arguments

Function has an arguments object containing all of the arguments passed by the called (even if function does not define any parameter, you can still pass arguments).

Arrow functions do not have this parameter.

Arrow Functions

this is inherited from the scope where arrow function was defined.

Functions' Functions

call()

call() allows to invoke any function in a context of any object.

let person = {
    name: "John"
}

function sayHi() {
    console.log('Hi, ', this.name)
}

sayHi.call(person) //Hi, John

If the function accepts arguments, we can pas them in via consecutive parameters of call.

apply()

Works like call(), but it accepts parameters as an array instead of consecutive parameters.

bind()

Creates a copy of a function in a context of some other object.

let person1 = {
    name: "John",
    sayName() {
        console.log(this.name)
    }
}

let person2 = {
    name: "Sophia"
}

let bound = person1.sayName.bind(person2)

bound() //Sophia

It doesn't modify person1 nor person2.

Rest

It behaves like params in C#. Rest can appear only at the end of the parameters list.

function sayNames(...names) {
    foreach (name of names) {
        console.log(name)
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment