The this Keyword Runtime Semantics – Part 2

Every Function Object Has Methods apply(), call() and bind().
All these methods useful to call an arbitrary function as if this function was declared as a method on a target object.
[table class=”table table-striped”]
Function,Function invoke,Scope Change,How to call,Args passing
Apply(),Yes,Yes,”Function.prototype.apply ( thisArg, argArray )”,As Array[]
Call(),Yes,Yes,”Function.prototype.call (thisArg , …args)”,As comma separated
Bind(),No,Yes,”Function.prototype.bind ( thisArg , …args)”,As comma separated
[/table]

share = {
 a52WeekHigh:100,
 a52WeekLow:55,
 publishValue:function (demandIncrease){
 var d = demandIncrease? '. Demand Increase By:'+demandIncrease+'%' : ''
 console.log("52 week High and Low:"+ this.a52WeekHigh+'-'+this.a52WeekLow + d);
 }
}
pqrShare={
 a52WeekHigh:99,
 a52WeekLow:17
}
share.publishValue(); //52 week High and Low:100-55
share.publishValue.apply(pqrShare); //52 week High and Low:99-17
share.publishValue.apply(pqrShare,[12]);
share.publishValue.call(pqrShare,13);
var bond = share.publishValue.bind(pqrShare,14);//function won't invoke
bond(); //52 week High and Low:99-17. Demand Increase By:14%

Output will come as following:

52 week High and Low:100-55
52 week High and Low:99-17
52 week High and Low:99-17. Demand Increase By:12%
52 week High and Low:99-17. Demand Increase By:13%
52 week High and Low:99-17. Demand Increase By:14%

Leave a Reply

Your email address will not be published. Required fields are marked *