call(), apply(), and bind()

node v10.16.3
version: 1.0.0
endpointsharetweet
var sayName = function(){ console.log("My name is " + this.name); } var stacey = { name: "Stacey", age: 34 } // Will call say name in the context of stacey. So 'this' will be stacey sayName.call(stacey);
var languages = ['Javascript', 'Ruby', 'Python'] var logItems = function(lang1, lang2, lang3){ console.log(lang1+ " " +lang2+ " " +lang3) } // Apply lets you pass in the arguments as an array logItems.apply(undefined, languages) // Call does not, and they must be listed out logItems.call(undefined, languages[0],languages[1],languages[2])
var languages = ['Javascript', 'Ruby', 'Python'] var logItems = function(lang1, lang2, lang3){ console.log(lang1+ " " +lang2+ " " +lang3) } // Bind behaves much like call, except it returns a new function that can be called later. // This way we can have functions with specific contexts ('this') and arguments var newFunc = logItems.bind(undefined, languages[0],languages[1],languages[2]) newFunc()
Loading…

no comments

    sign in to comment