gpt4 book ai didi

javascript - JavaScript 中的类

转载 作者:行者123 更新时间:2023-11-28 16:04:53 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com