Skip to content

Instantly share code, notes, and snippets.

@mojaray2k
Created August 25, 2018 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mojaray2k/0133279a4183e01fb16c46f8b018eb35 to your computer and use it in GitHub Desktop.
Save mojaray2k/0133279a4183e01fb16c46f8b018eb35 to your computer and use it in GitHub Desktop.
JS Bin// source http://jsbin.com/diqumox
/* Enhanced Object Literals */
const inventory = [
{ title: 'Harry Potter', price: 10 },
{ title: 'Eloquent Javascript', price: 15 }
];
// Object Literals the ES5 way example #1
function createBookshopES5(inventory) {
return {
inventory: inventory,
inventoryValue: function() {
return this.inventory.reduce((total, book) => total + book.price, 0);
},
priceForTitle: function(title) {
return this.inventory.find(book => book.title === title).price;
}
};
}
const bookShopES5 = createBookshopES5(inventory);
const totalInventoryES5 = bookShopES5.inventoryValue();
console.log(totalInventoryES5);
const bookPriceES5 = bookShopES5.priceForTitle("Harry Potter");
console.log(bookPriceES5);
// Object Literals the ES6 way example #1
function createBookshopES6(inventory) {
return {
inventory,
inventoryValue() {
return this.inventory.reduce((total, book) => total + book.price, 0);
},
priceForTitle(title) {
return this.inventory.find(book => book.title === title).price;
}
};
}
const bookShopES6 = createBookshopES6(inventory);
const totalInventoryES6 = bookShopES6.inventoryValue();
console.log(totalInventoryES6);
const bookPriceES6 = bookShopES6.priceForTitle("Harry Potter");
console.log(bookPriceES6);
// Object Literals the ES5 way example #2
const url = "http://fileupload.com";
const data = { color: 'red' };
function saveFileES5() {
$.ajax({ method: 'POST', url: url, data: data });
}
const newFileES5 = saveFileES5(url, data);
console.log(newFileES5);
// Object Literals the ES6 way example #2
function saveFileES6() {
$.ajax({ url, data, method: 'POST'});
}
const newFileES6 = saveFileES6(url, data);
console.log(newFileES6);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment