Is the constructor function prototype enumerable?
After reading several posts and documentation, I am still unclear about the true definition of an enumerated property. Moving forward, let me show you where I am confused:
I am creating a constructor and adding a prototype.
var myAlphabet = function() {
this.c = 5
this.d = 6
}
myAlphabet.prototype = {
e:7
}
Now I am creating a new instance of myAlphabet using the new keyword
var myObject = new myAlphabet();
Using a for-in loop, I want to console.log all the keys in the myObject instance (not the keys from the prototype).
for( key in myObj){
console.log(key);
}
This magazine:
'c'
'd'
'e'
According to the for..in loop documentation:
The for..in operator iterates over the enumerated properties of an object, in no particular order. For each individual property, statements can be executed.
Which makes me think the prototype is enumerable property
. But after reading the documentation forEnumerable properties
Property ownership is determined by whether the property belongs directly to the object rather than its prototype chain.
So the prototype created earlier is not directly on the myObject instance, it is included in the prototype chain. Why does it include this when I iterate over each key?
source to share
Why does it include this when I iterate over each key?
modeled on the prototype of javascript objects this is the way their values inherit
just as if you had classes
class:base
{
c:2
d:3
}
base
{
a:1
}
if you instantiated an object of type myAlphabet, it would have properties, the a,b and c
difference is that in languages with classes, the instance would "contain" all the values that it defines and those that are defined by the parent class
instance of class
{
a:1//because my parent told me so
c:2
d:3
}
in objects prototyping languages are derived from objects, which means the values are not in the instance itself, but in the instance that acts as the parent
object1
{
prototype:object2//hidden from enumerator
c:2
d:3
...//when enumerating include all from prototype
}
object2
{
prototype:null//hidden from enumerator
a:1
...//when enumerating include all from prototype
}
so you actually preserve inheritance the way it would work with classified languages, the main difference is that inheritance is done on the fly. Actually the values are indeed in the prototype object, if you change object2.a = new
when reading from the child alert(object1.a)
it will fetch the new updated value from the parentnew
if you need to know if an enumerated property is in the object itself, from the parent, you should use object1.hasOwnProperty(a)
source to share