0

问题

在这里,我创建了

  • 使用构造器的Owner对象
  • 使用构造器的Camera对象

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

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

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

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

请帮助我理解这个概念。并且还请提供一些参考,我可以掌握这个概念。

运行测试:代码片段@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 工作区

4

1 回答 1

2

您正在调用IIF 中的this.owner,this.make​​ 等等来进行摘要。但是在那个IIF里面,this指的是window对象;不是您正在构建的所有者对象。即你试图在字符串中使用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 的评论),但这回答了您的直接问题。


附录:您可以使用callor以不同的方式执行 IIF apply,从而传递应该在其中评估它们的上下文

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
}

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

于 2013-03-02T23:18:54.600 回答