2

Let we have the following JS code:

function doThis(){
    myKeys=[];
    var span= document.createElement("span");
    var parent=document.getElementById("parent");
    var child=document.getElementById("child");
    var submit=document.getElementById("submit");
    child.insertBefore(span,submit.nextSibling);
    Person.prototype={pr: "pr"};
    var p= new Person("Ivan", "Ivanov");
    myKeys.push(getAllKeyValuePair(Person));
    span.innerHTML=myKeys;
}
function getAllKeyValuePair(obj){
    var str="";
    for(var key in obj){
        try{
            str=str+"{"+key+", "+obj[key]+"}";
        }
        catch(e){
            console.log(key);
        }
    }
    return str;
}
function Person(name,surname){
    this.name=name;
    this.surname=surname;
}

JSFIDDLE we declare prototype property of Person constructor function at the line

Person.prototype={pr: "pr"};

But when I'm trying to print all property of Person I'm excepted that we have at least prototype properties which indicate to {pr: "pr"} object. But if we replace line

myKeys.push(getAllKeyValuePair(Person));

to the line

myKeys.push(getAllKeyValuePair(Person.prototype));

we can see the {pr, "pr"}. I don't understand this, please explain me why it's occurring?

1 Answer 1

3

getAllKeyValuePair(Person) asks for all the keys on the Person constructor function. Person.prototype properties are made available to instances that have been built by the constructor:

var p= new Person("Ivan", "Ivanov");
myKeys.push(getAllKeyValuePair(p));

The reason you don't see prototype when you ask for the properties of Person is that prototype is a non-enumerable property. You can see this with:

> Object.getOwnPropertyDescriptor(Person, "prototype");
  > Object {
        value: Object,
        writeable: true,
        enumerable: false,
        configurable: false
    }

If you want to enumerate over all of an object's own properties, use Object.getOwnPropertyNames(Person). Note that this does not capture properties inherited from the object's prototype chain (thus, we say the object's "own" properties, rather than inherited properties).

Sign up to request clarification or add additional context in comments.

2 Comments

I'm repeat that i'm interested to know: Why we cant see prototype property of Person explicit? I'm declare prototype property of Person at the line Person.prototype={pr: "pr"}; but function myKeys.push(getAllKeyValuePair(Person)); doesnt output it to a span.
@St.Antario: It's non-enumerable, which means that it won't be visited by your for in loop. Use Object.getOwnPropertyNames(Person) instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.