我正在 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/