为什么输出undefined?

时间:2013-03-02 21:36:40

标签: javascript

问题

在这里,我创建了

  • 使用contructor的Owner对象
  • 使用contructor的Camera对象

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

这可能是因为我在summary()this.owner等中编写this.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

1 个答案:

答案 0 :(得分:2)

您在用于制作摘要的IIF中呼叫this.ownerthis.make等等。但在IIF中,this指的是窗口对象;不是你正在构建的所有者对象。即您尝试在字符串中使用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 + ".";
}

此外,还有更好的方法来构建所有这些(请参阅Benjamin Gruenbaum的评论),但这可以回答您当前的问题。


附录:您可以使用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
}

但是,在你的情况下,所有这些都是不必要的。