Daniel Robinson
Daniel Robinson

Reputation: 14898

javascript object prototype property access

Here is a jsFiddle of my question: http://jsfiddle.net/4wyvv/1/

Basically:

//constructor function
function Maker(){
    var str;

    this.init = function(str){
        this.str = str;
    };

    this.msg = function(){
        return this.str;
    };
}

//object from Maker
var obj = new Maker();

obj.init("Hi my name is Dan");

//make sure everything exists and has worked as expected
Audit.Log(obj.msg());
//look in Maker.prototype for the constructor property
Audit.Log(obj.constructor);
//look in Maker.prototype for the constructor property
Audit.Log(Maker.prototype.constructor);

//now look for all makers prototype properties, this should list atleast "constructor"
for(var i in Maker.prototype){
    Audit.Log(i);
}

Why does the foreach loop not put out anything? It should at least put out constructor as I showed that Maker.prototype.constructor exists.

Upvotes: 0

Views: 1572

Answers (2)

Abid
Abid

Reputation: 7227

Some properties of object like "constructor" are hidden or to be more precise non-enumerable so they are not enumerated using a for in loop like this, In ECMA5 we have a method that can get all the properties

Object.getOwnPropertyNames(Maker.prototype)

this is give you

["constructor"]

Here is a detailed explanation : How to display all methods of an object in Javascript?

Upvotes: 2

Tamil
Tamil

Reputation: 5358

From MDN

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

Things like constructor, toString, hasOwnProperty are non enumerable properties and they won't be listed in for..in

Upvotes: 2

Related Questions