Ad. Javascript.info part 5 Flashcards
function obj f
time of function execution:
time of “this” binding:
future
future
function call f()
time of function execution:
time of “this” binding:
now
now
f.call()
time of function execution:
time of “this” binding:
now
now
f.apply()
time of function execution:
time of “this” binding:
now
now
f.bind()
time of function execution:
time of “this” binding:
future
now
CALL(), APPLY, BIND() attach ________ into function (or object) and the difference is in the function invocation (see below).
“this”
CALL / APPLY / BIND?
var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); }
say. ___(person1, ‘Hello’); // Hello Jon Kuperman
say. ___(person2, ‘Hello’); // Hello Kelly King
CALL
CALL / APPLY / BIND?
var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; var person2 = {firstName: 'Kelly', lastName: 'King'};
function say(greeting) { console.log(greeting + ' ' + this.firstName + ' ' + this.lastName); }
say. ___(person1, [‘Hello’]); // Hello Jon Kuperman
say. ___(person2, [‘Hello’]); // Hello Kelly King
APPLY
var person1 = {firstName: 'Jon', lastName: 'Kuperman'}; var person2 = {firstName: 'Kelly', lastName: 'King'};
function say() { console.log('Hello ' + this.firstName + ' ' + this.lastName); }
var sayHelloJon = say.\_\_\_(person1); var sayHelloKelly = say.\_\_\_(person2);
sayHelloJon(); // Hello Jon Kuperman
sayHelloKelly(); // Hello Kelly King
BIND
_____ and ________ are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.
Call and apply are pretty interchangeable. Just decide whether it’s easier to send in an array or a comma separated list of arguments.
__________ is a bit different as it returns a new function
bind()
GOOD OR BAD PRACTICE?
function sayHello() { console.log("hello"); }
Object.prototype.hello = sayHello;
Date.hello(); // Prints hello
BAD
2
The reason you don’t want to use Object.prototype.sayHi = function(){} is that once you do, everything that has Object in its prototype chain will be able to use sayHi. That’s the core of prototypical inheritance.
function sayHello() { console.log("hello"); }
Object.prototype.hello = sayHello;
Date.hello(); //
Prints hello
Function._______ and Function._______ use whatever function you are calling or applying at the moment of the call or apply.
call
apply
function say() { console.log(arguments); } say.\_\_\_\_\_\_(this, "a", "b"); say.\_\_\_\_\_\_\_(this, ["a", "b"]);
call
apply