Reputation: 27375
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?
Upvotes: 2
Views: 71
Reputation: 115920
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).
Upvotes: 3