Last active
June 5, 2016 23:52
-
-
Save williampsena/37b6d92069ca7a36c0abb4e62265c607 to your computer and use it in GitHub Desktop.
Javascript Call and Apply - ES5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function notifyClient(message) { | |
alert(message); | |
} | |
function sendMail(customer, total) { | |
notifyClient.call(this, 'TODO: Send mail, (' + String(customer.id) + ', ' + String(total) + ')'); | |
} | |
function getDeals() { | |
var product = arguments[0]; | |
var minPrice = arguments[1]; | |
product.price = Math.round(product.price * 0.9, 2); | |
if(product.price < minPrice) { | |
product.price = minPrice; | |
} | |
} | |
function ShopCart(){ | |
} | |
ShopCart.prototype.items = []; | |
ShopCart.prototype.customer = { id: 1 }; | |
ShopCart.prototype.total = function total() { | |
var total = 0; | |
var item; | |
for(var i=0, c=this.items.length; i<c; i++){ | |
item = this.items[i]; | |
total += item.price * item.quantity; | |
} | |
return total; | |
}; | |
ShopCart.prototype.addItem = function addItem(product) { | |
this.getDealsByProduct(product); | |
this.items.push(product); | |
notifyClient.call(this, 'Item added ' + product.name); | |
}; | |
ShopCart.prototype.getDealsByProduct = function getDealsByProduct(product) { | |
getDeals.apply(this, [product, product.price * 0.6]); | |
}; | |
ShopCart.prototype.placeOrder = function placeOrder() { | |
sendMail.apply(this, [this.customer, this.total()]); | |
}; | |
var shopCart = new ShopCart(); | |
shopCart.addItem({ | |
id: 1, | |
name: 'Xbox Game', | |
price: 179, | |
quantity: 1 | |
}); | |
shopCart.placeOrder(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment