i saw this code online and this is its contents.
var shoppingcart = (function () {
var _calculatePrice = function() {
return this.price * this.amount;
};
return {
calculatePrice : _calculatePrice
}
})();
var goods = {
name: 'hammer',
price: 199,
amount: 2
}
shoppingCart.calculatePrice.call(goods)
And this is where i am not comfortable. the function returning an undefined object in {calculatePrice : _calculatePrice}. how does that really work? i thought it will do no harm to return just _calculatePrice
Firstly Typo at line 1.: change shoppingcart
to shoppingCart
var shoppingCart = (function() { var _calculatePrice = function() { return this.price * this.amount; }; return { calculatePrice: _calculatePrice } })(); var goods = { name: 'hammer', price: 199, amount: 2 } console.log(shoppingCart.calculatePrice.call(goods))
Explanation:
The returned object is:
{
calculatePrice: _calculatePrice
}
It's property calculatePrice
is variable _calculatePrice
.
_calculatePrice
references a function that returns a calculated Number.
.call()
function helps you call a function with reference at global scope. Thats why the calculation function uses this.price
& this.amount
.
There is a typo : you declare a var shoppingcart and then you call it shoppingCart with C instead of c.
try to change de var declaration to: var shoppingCart = ....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.