繁体   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