Skip to content

Instantly share code, notes, and snippets.

@williampsena
Created June 5, 2016 23:53
Show Gist options
  • Save williampsena/44ee4665ab0884eb07f1ff76bffbbd63 to your computer and use it in GitHub Desktop.
Save williampsena/44ee4665ab0884eb07f1ff76bffbbd63 to your computer and use it in GitHub Desktop.
Javascript Call and Apply - ES6
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;
}
}
class ShopCart{
constructor() {
this.items = [];
this.customer = { id: 1 };
}
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;
}
addItem(product) {
this.getDealsByProduct(product);
this.items.push(product);
notifyClient.call(this, 'Item added ' + product.name);
}
getDealsByProduct(product) {
getDeals.apply(this, [product, product.price * 0.6]);
}
placeOrder() {
sendMail.apply(this, [this.customer, this.total()]);
}
};
var shopCart = new ShopCart();
shopCart.addItem({
id: 1,
name: 'Xbox Game',
price: 179.00,
quantity: 1
});
shopCart.placeOrder();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment