对象#<person>没有方法'carName'</person>

时间:2012-02-03 02:24:06

标签: javascript

所以我得到了这个错误;对象#没有方法&#39; carName&#39; 但我清楚地做到了。 Pastebin

我也试过引用汽车&#34;型号&#34;财产

player.car.model

但是这不起作用,我得到了一个类型错误。有任何想法吗?你需要更多信息吗?

function person(name, car) {
    this.name = name;
    this.car = car;
    function carName() {
        return car.model;
    }
}

var player = new person("Name", mustang);
var bot = new person("Bot", mustang);
var bot2 = new person("Bot 2", mustang);

function makeCar(company, model, maxMPH, tireSize, zeroToSixty) {
    this.company = company;
    this.model = model;
    this.maxMPH = maxMPH;
    this.tireSize = tireSize;
    this.zeroToSixty = zeroToSixty;
}

var mustang = new makeCar("Ford", "Mustang GT", 105, 22, 8);
var nissan = new makeCar("Nissan", "Nissan 360z", 100, 19, 6);
var toyota = new makeCar("Toyota", "Toyota brandname", 95, 21, 7);

1 个答案:

答案 0 :(得分:3)

它没有这个方法。它有一个函数,它是构造函数的变量范围的本地函数。

要为每个对象提供函数,请将其指定为属性...

function person(name, car) {
    this.name = name;
    this.car = car;
    this.carName = function() {
        return this.car.model;
    };
}

或者更好,将它放在构造函数的prototype上......

function person(name, car) {
    this.name = name;
    this.car = car;
}

person.prototype.carName = function() {
    return this.car.model;
};

此外,当您将mustang传递给person构造函数时,{{1}}未初始化。