Here is an attempt to clear up things a bit.
<script>
var shoppingCart = (function () {
function calculatePriceNow() {
return this.price * this.amount;
};
return {
calculatePrice: calculatePriceNow
}
})();
var goods = {
name: 'hammer',
price: 199,
amount: 2
};
// will not work; Why? Because the function `calculatePrice` depends on their scope (`this`)
var result = shoppingCart.calculatePrice(goods);
console.log(result);
// will work; Why? We are calling the function giving it's scope explicitly using `call`
var result = shoppingCart.calculatePrice.call(goods);
console.log(result);
// will work; Why? We are calling the function giving it's scope explicitly using `apply`
var result = shoppingCart.calculatePrice.apply(goods);
console.log(result);
// How did it work with `call` and `apply`?
// They are executing `calculatePrice` in the scope of the argument `goods` which we passed to the function
// Doing so, the usage of `this` inside the function `calculatePrice` refer to the object `goods`
// Difference between `call` and `apply`?
// From MDN:
// The `apply()` method calls a function with with a given `this` value and `arguments` provided as array
// On the other hand, `call()` method calls a function with a given `this` value and `arguments` provided individually
</script>
Notes:
Will not work; Why? Because the function calculatePrice depends on its scope (this)
var result = shoppingCart.calculatePrice(goods);
console.log(result);
Will work; Why? We are calling the function giving it's scope explicitly using call
var result = shoppingCart.calculatePrice.call(goods);
console.log(result);
Will work; Why? We are calling the function giving it's scope explicitly using call
var result = shoppingCart.calculatePrice.apply(goods);
console.log(result);
How did it work with call and apply?
They are executing calculatePrice in the scope of the argument goods which we passed to the function. Doing so, the usage of this inside the function calculatePrice refer to the object goods.
Difference between call and apply?
The apply() method calls a function with with a given this value and arguments provided as array
On the other hand, call() method calls a function with a given this value and arguments provided individually
To the queries:
Why second snippet gives error instead of answer?
Like mentioned above, when we call like that the scope is that of the function, not of the 'argument'
What is the importance of using 'call' in the first method? Cannot
simple function also return the same answer?
Simple answer would we that we are giving it explicit scope using call
What is advantage of call over apply and bind if same used in this
example?
call(), apply() and bind() are part of all function object in JavaScript. The usage of it varies as mentioned above.
The advantages over call() and apply() is the flexibility on calling a method (say with different arguments).