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 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 に答える
0

あなたの「クラス」は他のJavaScript基本クラスから(あなたの場合は透過的に)継承するためです。オブジェクトで作成したプロパティのみをイントロスペクトする場合は、 を使用hasOwnProperty(keyName)してそれらを除外します。

于 2013-03-18T18:16:14.940 に答える