Classes in JavaScript

Classes in JavaScript

本文关键字:JavaScript in Classes      更新时间:2023-09-26

我在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语句中,我得到的不仅仅是这个类,我得到的基本上是所有其他正在发生的事情的各种信息。为什么呢?

关键字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();

因为你的"class"继承了(在你的例子中是透明的)其他javascript基类。如果您只想内省您在对象上创建的属性,请使用hasOwnProperty(keyName)将其过滤掉。

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.