Skip to content

Instantly share code, notes, and snippets.

@aneurysmjs
Last active September 30, 2019 08:06
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 aneurysmjs/a1ee012424cf550274cc372c9864b52b to your computer and use it in GitHub Desktop.
Save aneurysmjs/a1ee012424cf550274cc372c9864b52b to your computer and use it in GitHub Desktop.
couple of tricks about prototypal inheritance
/**
* understanding .constructor property
*/
function User() {
}
// when functions are created, they're given a "prototype" property which is an object
console.log(User.prototype); // {}
// tne only property of that prototype object is "constructor" which points back to the function that was created with
console.log(User.prototype.constructor); // User
const jero = new User();
console.log(jero.constructor === User) // true;
/**
* Looping over properties
*/
const user = {
name: 'Jero',
url: 'https://someurl.com'
};
let i = 0;
for (property in user) {
i += 1;
}
i // 2
// Loops can behave differently when objects have chained prototype objects.
const user = {
name: 'Jero',
url: 'https://someurl.com'
};
const protoUser = {
email: 'some@email.com'
};
Object.setPrototypeOf(user, protoUser);
let i = 0;
for (property in user) {
i += 1;
}
i // 3, and that's because for-in loop steps through the prototype chain object-by-object
// to avoid that just simply iterate over object's own properties
for (property in user) {
if(obj.hasOwnProperty(property)){
i += 1;
}
}
i // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment