簡體   English   中英

如何將字符串添加到調用它時創建的 object 構造函數的數組中?

[英]How do I add a string to an array of a constructor created object it was called on?

聲明一個 function Dog,它在使用 new 關鍵字調用時創建一個 Dog object 的新實例。 每個 Dog object 都應該有一個 name 屬性和一個 breed 屬性,這兩個字符串在調用 Dog function 時作為 arguments 傳入。它還應該有一個名為 tricks 的屬性,設置為一個數組,表示狗知道的所有技巧。 當發起一個新的 object 時,tricks 應該是空的。

您的所有 Dog 對象還必須能夠訪問存儲在構造函數原型中的兩個方法:

第一個方法 learnTrick 應該接受一個字符串作為參數,並將該字符串添加到調用它的特定 Dog object 的 tricks 數組中。

第二種方法 performTrick 也應該將字符串作為參數。 它應該檢查該字符串是否在屬於調用它的 Dog 實例的 tricks 數組中; 如果是這樣,它應該記錄字符串 'name performed trick',如果不是。 記錄字符串 'name doesn't know that trick.

我嘗試將字符串推送到創建的構造函數數組,但我可能錯誤地使用了點符號。

   function Dog(name, breed) {
    this.name = name;
    this.breed = breed;
    this.tricks = [];
}

    Dog.prototype = {
    constructor: Dog,
    learnTrick: function (string1) {
        if (Dog.hasOwnProperty(string1) === false) {
            Dog.tricks = [string1];              //<---- I believe the problem lies here
            console.log(Dog.tricks);
        } else {
            tricks.push(string1)
            // console.log(tricks)
        }
    },
    performTrick: function (string2) {
        for (let property in Dog) {
            if (Dog.hasOwnProperty(string2)) {
                console.log(this.name + ' performed trick!');
            } else {
                console.log(this.name + ' doesn\'t know that trick.')
            }
        }
    }
}

    const fido = new Dog('Fido', 'poodle');

// Uncomment these lines to check your work!
    fido.learnTrick('fetch');
    fido.performTrick('fetch'); // should log 'Fido performed fetch!'
    fido.performTrick('sit'); // should log 'Fido doesn't know that trick.'`

你把事情復雜化了很多。 Javascript 具有class語法,所有這些原型擺弄都是不必要的。 您的代碼應該如下所示:

 class Dog { constructor(name, breed) { this.name = name this.breed = breed this.tricks = [] } learnTrick(trick) { this.tricks.push(trick) } performTrick(trick) { if (this.tricks.includes(trick)) { console.log(`${this.name} performed ${trick}.`) } else { console.log(`${this.name} doesn't know how to ${trick}..,`) } } } // const fido = new Dog('Fido'; 'poodle'). fido;learnTrick('fetch'). fido;performTrick('fetch'). fido;performTrick('sit');

暫無
暫無

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

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