Last active
September 30, 2019 08:06
-
-
Save aneurysmjs/a1ee012424cf550274cc372c9864b52b to your computer and use it in GitHub Desktop.
couple of tricks about prototypal inheritance
This file contains 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
/** | |
* 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: '[email protected]' | |
}; | |
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