javascript - JavaScript 中的类

标签 javascript class

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

关于javascript - JavaScript 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15483884/

相关文章:

java - Java 中私有(private)静态嵌套类中的访问修饰符

c++ - 自动生成基于成员的操作?

javascript - 使用提交表单填充表(javascript)

javascript - JQuery FAQ slider 答案不会隐藏?

c++ - 如何从构造函数中确定类的内存分配地址?

android - 如何在 android 中解决此错误 "com.android.internal.telephony cannot be resolved to a type"

java - 使用泛型和动态类类型返回类型转换

javascript - 使用正则表达式和 javascript 每 2 个单词插入回车符

javascript - 如何使用 javascript 查找 json 中的通用名称对象

javascript - 为什么这些对象属性未定义?