简体   繁体   中英

Constructor functions prototype enumerable?

After reading a few posts and documentation I am still unclear on the true definition of an enumerable property. Moving forward, let me show you where I am confused:

I create a constructor function and add a prototype.

var myAlphabet = function() {
  this.c = 5
  this.d = 6
}

myAlphabet.prototype = {
  e:7
}

Now I create 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 instance of myObject (not keys from the prototype).

for( key in myObj){
    console.log(key);
}

This logs:

'c'
'd'
'e'

According to the for..in loop documentation:

The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

Which makes me believe that the prototype is an enumerable property . But reading the documentation for Enumerable properties

Ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain.

So the prototype created earlier is not directly on the instance of myObject, it is included in the prototype chain. Why is it including this when I loop over each key?

Why is it including this when I loop over each key?

it is by design of the javascript's objects prototype is the way of them inheriting values

the same way that if you had classes

class:base
{
    c:2
    d:3
}
base
{
    a:1
}

if you instantiated a object of type myAlphabet it would have properties a,b and c the difference is that in languages with classes the instance would "contain" all the values the ones defined by it and the ones defined by the parent class

instance of class
{
    a:1//because my parent told me so
    c:2
    d:3
}

in prototyping languages objects derive from objects which means the values do not resides in the instance itself but on the instance that acts as 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 virtually maintain inheritance just like it would work with classed languages the main difference being, the inheritance is made on the fly.. and the values actually reside in the prototype object if you change object2.a = new when you read from child alert(object1.a) it will fetch the new updated value from the parent new

if you need to know if a enumerated property resides in the object itself of is being fetched from the parent you have to use object1.hasOwnProperty(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM