Reputation: 242
I am defining a class in JavaScript
function Pen(parent){
this.color = "#0000ff";
this.stroke = 3;
this.oldPt;
this.oldMidPt;
this.isActive = false;
this.parent = parent; //app that owns this pen
this.points = [];
this.curShape;
console.log(this);
return(this);
}
In the console.log statement I am getting way more than just this class, I am getting all kinds of information about basically everything else going on. Why is that?
Upvotes: -1
Views: 130
Reputation: 362
Javascript is prototype based and not class based. Every new custom object as default
has pre built functionlity provided by the base object called Object.
So everytime you ask if a property or method belongs to a given object, in the worst
case it will fall until the Object object, and if that property/method is not there
then it will throw an error. Therefore when you are using the log function it is
printing all the object structure including properties and method of its "base" class.
Upvotes: 0
Reputation: 1082
Because your "class" inherits (transparently, in your case) from other javascript base classes. If you want to introspect only the properties you've created on your object, use hasOwnProperty(keyName)
to filter those out.
Upvotes: 0
Reputation: 4808
the keyword this
is dependent on the caller, so if you are initializing the function without the "new" keyword "this" might very well be referencing the window and not the object.
Try:
function Pen(parent){
var context = this;
this.color = "#0000ff";
this.stroke = 3;
this.oldPt;
this.oldMidPt;
this.isActive = false;
this.parent = parent; //app that owns this pen
this.points = [];
this.curShape;
console.log(context);
return(this);
}
var pen = new Pen();
Upvotes: 4