0

我在 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);
} 

在console.log 语句中,我得到不仅仅是这个类,我得到了关于基本上所有其他事情的各种信息。这是为什么?

4

3 回答 3

4

关键字this取决于调用者,因此如果您在没有“new”关键字的情况下初始化函数,“this”很可能是在引用窗口而不是对象。

尝试:

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();
于 2013-03-18T18:14:35.627 回答
0

因为您的“类”从其他javascript基类继承(在您的情况下是透明的)。如果您只想内省您在对象上创建的属性,请使用hasOwnProperty(keyName)过滤掉这些属性。

于 2013-03-18T18:16:14.940 回答
0
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.
于 2013-03-18T18:30:39.857 回答