Prototypes Continued
Last updated
Last updated
While the prototype chain is pretty awesome, it can only be used to access certain properties/methods/functions (Which term or terms is best to use here?). There are really two ways to figure out which properties can be accessed: 1. Exactly what we did previously; typing the (prototype?) object name followed by a period .
2. Entering the name followed by __.proto.__
or .prototype
__.proto.__
(two underscores on each side) is only used on the base of your prototype chain, person1
in our case (correct?). You can use it to get a better understanding of the prototype chain's path.
.prototype
is used in every other link of the chain (correct?). Without it, you won't be able to use functions such as isPrototypeOf
or valueOf
. Please note that these are advanced topics and you probably won't need to go this much in depth for awhile.
Remember earlier how we used something called Object.create()
to create objects? Let's learn more about it now.
Let's create a new object instance calledperson2
.
At first glance you may think something's up, it looks just like person1
! While the data looks exactly the same (name, age, etc.), it's not really a copy, person2
is just using person1
's prototype as a prototype object.
You can confirm this by running person2.__proto__
.
See, the Person
object, person1
's prototype, is returned.
There's also a .constructor
property that allows you to see the properties available to object instances created using that constructor. For example, both person1.constructor
and person2.constructor
return:
the Person()
constructor.
If for some reason you don't have a reference to the original constructor and want to create a new reference, you're in luck! You can create a new instance like so:
The .constructor
property can also help you find the constructor name based on an instance name, for example:
returns "Person".
If you really needed to modify the .prototype
property, you can. Let's add a goodbye message to our code.
person1.farewell()
returns the following:
You shouldn't use this concept often however. For example:
This doesn't work because it's not that flexible. Even something like this
would give you undefined
because the global scope is being referenced rather than the function scope.
Moral of the story is: If you really want to define properties on the prototype make sure they are static, constant properties. Otherwise, it's generally best to just define them on the constructor.