Last active
November 6, 2017 03:20
-
-
Save maumchaves/336ed0549142043024c408795663181f to your computer and use it in GitHub Desktop.
JavaScript Anomalies.
This file contains hidden or 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
// #1 - Context. The `this` variable case: | |
var Person = function(firstname) { | |
this.firstname = firstname; | |
this.print = function() { | |
setTimeout(function () { | |
console.log("My name is " + this.firstname); | |
}); | |
} | |
} | |
var mau = new Person("Mauricio"); | |
console.log(mau.firstname); // Prints "Mauricio". | |
mau.print(); // We expect "My name is Mauricio" but instead it prints "My name is undefined". | |
// A possible solution: | |
Person = function(firstname) { | |
this.firstname = firstname; | |
this.print = function() { | |
setTimeout(() => { | |
console.log("My name is " + this.firstname); | |
}); | |
} | |
} | |
mau = new Person("Mauricio"); | |
console.log(mau.firstname); // Prints "Mauricio". | |
mau.print(); // We finally printed "My name is Mauricio". | |
// #2 - Object Reference. | |
// Extending the code above: | |
function setAge(person, age) { | |
person.age = age; | |
} | |
var javi = mau; | |
setAge(mau, 26); | |
console.log(mau.age); // It prints 26 as expected. | |
console.log(javi.age); // But it also changed the age for `javi`. This could be tricky. | |
// A possible solution: deep clone. | |
javi = Object.assign(new Person(), mau); | |
javi.firstname = "Javi"; | |
setAge(javi, 28); | |
console.log(mau); // The instance `mau` keeps their original properties. | |
console.log(javi); // Changes in `javi` only affected this specific instance. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment