diff --git a/notes/chapter5_javascript-objects.md b/notes/chapter5_javascript-objects.md index 2e2e6cc..cd5e725 100644 --- a/notes/chapter5_javascript-objects.md +++ b/notes/chapter5_javascript-objects.md @@ -20,3 +20,10 @@ Parse objects into function just like normal number, it allow us to parse multip Exmple check [object-function.js](../src/objects/objects-functions.js) +## Object References + +When a object is parsed as argument into function, it's parsed as reference (not as a copy). Changes done by function on object affect original object + +But when a new value to the argument (in function), it break the binding (pass as reference) within function. But does not affect the original object + +Example check [object-references.js](../src/objects/objects-references.js) \ No newline at end of file diff --git a/src/objects/objects-references.js b/src/objects/objects-references.js new file mode 100644 index 0000000..b5918a1 --- /dev/null +++ b/src/objects/objects-references.js @@ -0,0 +1,20 @@ +let myAccount = { + name: "Andrew Mead", + expenses: 0, + income: 0 +} + +let addExpense = function (account, amount) { + account.expenses = account.expenses + amount + console.log(account) +} + +addExpense(myAccount, 2.5) // => { name: 'Andrew Mead', expenses: 2.5, income: 0 } +addExpense(myAccount, 5.2) // => name: 'Andrew Mead', expenses: 7.7, income: 0 } + +addExpense = function (account, amount) { + account = {} + console.log(account) // => {} as it break binding +} +addExpense(myAccount, 2.5) +console.log(myAccount) // => { name: 'Andrew Mead', expenses: 7.7, income: 0 } \ No newline at end of file