簡體   English   中英

構造函數未顯示正確的結果

[英]constructor function not showing correct results

我是這里的新手。 我試圖創建一個汽車對象和實例。 該代碼是

  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();

現在,我在瀏覽器中什么都看不到。 請告訴我我在做什么錯。 非常感謝!。

您正在將功能引用describeCar分配給Cardescribe屬性,因此

mercedes.describe();
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();

您應該調用類函數名稱而不是已定義的名稱。

describeCar是一個函數,因此,如果要在構造函數中使用它,則需要用括號括起來並以“ this”作為引用:

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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM