Peterson Peterson - 2 months ago 7
Javascript Question

Using call in JavaScript vs Returning by simple function

These are the 2 methods to calculate total amount based on object data:

Snippet 1



var shoppingCart = (function(){
function calculatePriceNow() {
return this.price * this.amount;
};
return {
calculatePrice : calculatePriceNow
}
})();

var goods = {
name : 'hammer',
price: 199,
amount : 2
};

var result = shoppingCart.calculatePrice.call(goods);
console.log(result);





Snippet 2



var shoppingCart = (function(){
function calculatePriceNow(obj) {
return obj.price * obj.amount;
};
})();

var goods = {
name : 'hammer',
price: 199,
amount : 2
};

var result = shoppingCart.calculatePriceNow(goods);
console.log(result);





Result 1:

398

Result 2:

enter image description here

My Query


  1. Why second snippet gives error instead of answer?

  2. What is the importance of using 'call' in the first method? Cannot simple function also return the same answer?

  3. What is advantage of call over apply and bind if same used in this example?


Answer

I'll try to address each of your questions.

Why second snippet gives error instead of answer?

Because, you are using an IIFE, yet you are return nothing. If you do not explicitly return something in javascript (in a function) it is implied to return undefined. Thus your error "cannot... of undefined". So you'd want to return that function, that you have inside of it.

What is the importance of using 'call' in the first method? Cannot simple function also return the same answer?

The important of call (and apply) is the ability to "bind" the context. So, in your snippet 1 - do you see the references to this. Well, when you call the function with call - you are "binding" the context of goods to this. So, when you say this.price, you are saying goods.price. Because call enables you to do that.

What is advantage of call over apply and bind if same used in this example?

Others might know the intricacies, but I believe call is fine in this context. IF, you were passing some arguments in addition to setting the "context" - like an array, then you'd use apply. The usage of bind returns a new function, so there is a memory cost there. It is like partial application - you give an argument, the context - and it returns a new function - waiting. I'd say in your usage, call is perfect. I'd like to hear what others think.

Comments