gpt4 book ai didi

javascript - 为什么输出未定义?

转载 作者:行者123 更新时间:2023-12-02 18:57:40 25 4
gpt4 key购买 nike

问题

在这里,我创建了

  • 使用构造函数的 Owner 对象
  • 使用构造函数的 Camera 对象

在第二个输出语句中,我希望它显示为第一个语句,但它显示未定义。

这可能是因为我编写 summary() 方法的方式,如 this.ownerthis.make、等等

注意:- 第一个输出语句从构造函数外部访问变量值。但在第二个输出语句中,summary() 方法访问构造函数本身内部的变量。

不应该以这种方式使用 make 变量(而不是参数)吗?如何在对象构造函数中使用它们?

请帮我理解这个概念。另外,请提供一些我可以理解这个概念的引用。

运行测试:Code Snippet @ CodeAcademy Workspace

代码片段

//camera object contructor
function Camera(model, make, year, owner)
{
this.make = make.toString();
this.model = model.toString();
this.year = parseInt(year);
this.owner = function(){
return (owner.fname + " " + owner.lname).toString();
}();
this.summary = function(){
return this.owner + " bought a " + this.make + " " + this.model + ", released in " + this.year + ".";
}();
}

//owner object contructor
function Owner(fname, lname){
this.fname = fname;
this.lname = lname;
}

//create owner
var niky = new Owner("Niky", "Bauxi");
//create camera for owner
var niky_cam = new Camera("DSLR D3100", "Nikon", 2009, niky);

console.log(niky_cam.owner + " bought a " + niky_cam.make + " " + niky_cam.model + ", released in " + niky_cam.year + ".");
console.log(niky_cam.summary);

输出

Niky Bauxi bought a Nikon DSLR D3100, released in 2009.
undefined bought a undefined undefined, released in undefined.

解决方案

考虑不同的答案和评论后,

解决方案1:CodeAcademy workspace

最佳答案

您在用于生成摘要的 IIF 中调用 this.ownerthis.make 等。但在该 IIF 内部,this 引用了窗口对象;不是您正在构造的所有者对象。 IE。您尝试在字符串中使用 window.ownerwindow.make 等,但它们不存在。

试试这个

function Camera(model, make, year, owner) {
this.make = make.toString();
this.model = model.toString();
this.year = parseInt(year, 10); // ALWAYS supply a radix argument!
this.owner = (function(){
return (owner.fname + " " + owner.lname).toString();
}());
var that = this;
this.summary = (function(){
return that.owner + " bought a " + that.make + " " + that.model + ", released in " + that.year + ".";
}());
}

但是 IIF 从一开始就毫无意义。您也可以这样做:

function Camera(model, make, year, owner) {
this.make = make.toString();
this.model = model.toString();
this.year = parseInt(year, 10);
this.owner = owner.fname + " " + owner.lname;
this.summary = this.owner + " bought a " + this.make + " " + this.model + ", released in " + this.year + ".";
}

此外,还有更好的方法来构建所有这些(请参阅本杰明·格伦鲍姆的评论),但这回答了您直接的问题。

<小时/>

附录:您可以使用 callapply 执行不同的 IIF,从而传递应在其中进行评估的上下文

function Camera(model, make, year, owner) {
// ...
this.summary = (function(){
return this.owner + " bought a " + this.make + " " + this.model + ", released in " + this.year + ".";
}).call(this); // explicitly pass the current context to the function
}

但是,同样,所有这些对于您的情况来说都是不必要的。

关于javascript - 为什么输出未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180461/

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