构造函数没有显示正确的结果

时间:2015-05-08 00:52:26

标签: javascript

我在这里是个新手。 我正在尝试创建一个汽车对象和实例。 代码是

  function Car(name, speed) {
        this.name = name;
        this.speed = speed;
        this.describe=describeCar;
    };


    function describeCar(){
        document.write("The Full name is " + this.name + " and the top speed is " + this.speed);
    };

    var mercedes = new Car("Mercedes benz", 233); // Instance of Object
    var bmw = new Car("British motor Works", 260); // Instance of Object
    mercedes.describeCar();

现在我在浏览器中看不到任何内容。 请告诉我我做错了什么。 非常感谢!。

3 个答案:

答案 0 :(得分:1)

您正在将函数参考describeCar分配给describe的{​​{1}}属性,以便

Car

答案 1 :(得分:1)

function Car(name, speed) {
        this.name = name;
        this.speed = speed;
        this.describe=describeCar;
    };


    function describeCar(){
        document.write("The Full name is " + this.name + " and the top speed is " + this.speed);
    };

    var mercedes = new Car("Mercedes benz", 233); // Instance of Object
    var bmw = new Car("British motor Works", 260); // Instance of Object
mercedes.describe();

<强> mercedes.describe();

您应该调用类函数名称而不是已定义的函数名称。

答案 2 :(得分:-2)

describeCar是一个函数,所以需要括号来调用它和&#34;这个&#34;如果你想在构造函数中使用它作为参考:

function Car(name, speed) {
    this.name = name;
    this.speed = speed;
    this.describe=this.describeCar();
};

Car.prototype.describeCar = function(){
    return "The Full name is " + this.name + " and the top speed is " + this.speed;
};

var mercedes = new Car("Mercedes benz", 233); // Instance of Object
var bmw = new Car("British motor Works", 260); // Instance of Object
document.write(mercedes.describe);

http://jsfiddle.net/nzv7jjch/

如果你只需要函数输出,那么只需调用函数并避免在构造函数中使用它:

function Car(name, speed) {
    this.name = name;
    this.speed = speed;
};

Car.prototype.describeCar = function(){
    return "The Full name is " + this.name + " and the top speed is " + this.speed;
};

var mercedes = new Car("Mercedes benz", 233); // Instance of Object
var bmw = new Car("British motor Works", 260); // Instance of Object
document.write(mercedes.describeCar());