Object Prototypes Flashcards
How do you check for property existence in an object?
using the ‘in’ operator or the .hasOwnProperty method
How do you use the ‘in’ method?
“false” in myObject // true
“true” in myObject // false
how do you use the .hasOwnProperty() method?
myObject.hasOwnProperty(“7”) // true
myObject.hasOwnProperty(“8”) // false
What is the difference between an object prototype and a function prototype?
The object that an object inherits properties and methods from is called theobject prototype. the object that a function references is called its function prototype. It automatically sets the object prototype of any object it creates to this function prototype. Functions also have object prototypes since they are in fact objects.
What happens when we call ‘new’?
When we usenew
to calla class ‘Cat’, JavaScript first creates a new empty object. In practice, that means the new object has access to the methods defined by theCat
class.
It then sets the new object’s object prototype toCat
’s function prototype. It then callsCat
’sconstructor
method withthis
set to the new object. Theconstructor
method initializes the new object, then returns the object to the caller.
What does Object.create() do?
The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object.
What does a for/in loop do?
Afor/inloop iterates over an object’s properties. The iteration includes properties from the objects in its prototype chain. UsehasOwnPropertyto skip the prototype properties.
what does Object.keys() do?
Object.keysreturns an object’s “own” property keys – you do not need to usehasOwnProperty.
What is the prototype chain?
This chain is the list of prototypes going back to the default object prototype. ie
c –> b –> a –> Object.prototype –> null
how does property lookup work in the prototype chain?
When you access a property on an object, JavaScript first looks for an “own” property with that name on the object. If the object does not define the specified property, JavaScript looks for it in the object’s prototype. If it can’t find the property there, it next looks in the prototype’s prototype. This process continues until it finds the property or it reachesObject.prototype. IfObject.prototypealso doesn’t define the property, the property access evaluates toundefined.
What happens if you set a property on an object which has the same property in its prototype chain?
When assigning a property on a JavaScript object, it always treats the property as an “own” property. That is, it assumes that the property belongs to the object named to the left of the property name. The prototype will not be modified even if it has a property of the same name.
How can you tell if one object is a prototype of another?
animalPrototype.isPrototypeOf(conor)
//true