Something Like that:
call(), apply() and bind()
For that you need to create first html code.
HTML
<p id="demo1"></p> <p id="demo2"></p> <p id="demo3"></p>
After that add this JS code.
JS
var person = {
firstname: 'John',
lastname: 'Doe',
getFullName: function(){
var fullname = this.firstname + ' ' + this.lastname;
return fullname;
}
}
var logName = function(lang1, lang2){
document.getElementById('demo1').innerHTML = 'Logged: ' + this.getFullName();
document.getElementById('demo2').innerHTML = 'Arguments: ' + lang1 + ' ' + lang2;
document.getElementById('demo3').innerHTML = '-------';
}
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”brLEYQ” default_tab=”result” user=”pradeepanvi”]See the Pen call, apply and bind in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Right now we can’t see anything. Because we didn’t use these three call(), apply() and bind()
bind()
For a given functions, creates a bound function that has the same body as the original function.
The this object of the bound functions is associated with the specified object, and has the specified initial parameters.
JS
var logPersonName = logName.bind(person); logPersonName();
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”qXxbym” default_tab=”result” user=”pradeepanvi”]See the Pen bind in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Logged: John Doe
Arguments: undefined undefined
——-
call()
Calls a method of an object, substituting another object for the current object.
JS
logName.call(person, 'en', 'es');
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”JypGaW” default_tab=”result” user=”pradeepanvi”]See the Pen call in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Logged: John Doe
Arguments: en es
——-
apply()
Calls the function, substituting the specified object for the this value of the function,
and the specified array for the arguments of the function.
JS
logName.apply(person, ['en', 'es']);
[codepen_embed height=”265″ theme_id=”0″ slug_hash=”dzdGgZ” default_tab=”result” user=”pradeepanvi”]See the Pen apply in javascript by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]
Now you can see
Logged: John Doe
Arguments: en es
——-