Skip to content

Instantly share code, notes, and snippets.

@maumchaves
Last active November 6, 2017 03:20
Show Gist options
  • Save maumchaves/336ed0549142043024c408795663181f to your computer and use it in GitHub Desktop.
Save maumchaves/336ed0549142043024c408795663181f to your computer and use it in GitHub Desktop.
JavaScript Anomalies.
// #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