Functions

Function Assignment in JavaScript

Used to call and/or provide the context (object) for a function that is dependant on an object. Often, functions are assigned to objects and access object members using the 'this' keyword.


Syntax
//applies object to function and calls the function, object applied only for that call
functionName.call(assignedObject, passedParams);
//apply is identical, but takes an array of params
functionmae.apply(assignedObject, [passedParams]);

//permanent assignment of an object to a function
functionName.bind(assignedObject);
//object assigned to all subsequent function calls without specifying it
functionName(passedParams);

Notes

Typically used when a function depends on different object types, or for passing parameters.


Example
var gradesList = {
    grades: "80, 90, 60";
}
//append grade depends on list of grades from another object
var appendGrade = function(grade) {
    return this.grades + ", " + grade;
}

//function call, providing the object
appendGrade.call(gradesList, '85');

< Closures   |   Object Declaration >

© 2019 SyntaxDB. All Rights Reserved.