如何将字符串添加到调用它的构造函数创建的对象的数组中?

问题描述 投票:0回答:2

声明一个函数 Dog,当使用 new 关键字调用时,该函数创建 Dog 对象的新实例。每个 Dog 对象都应该有一个 name 属性和一个 Breed 属性,这两个字符串在调用 Dog 函数时作为参数传入。它还应该有一个名为“技巧”的属性,设置为一个表示狗知道的所有技巧的数组。当启动一个新对象时,tricks 应该为空。

所有 Dog 对象还必须有权访问存储在构造函数原型上的两个方法:

第一个方法 learnTrick 应该接受一个字符串作为参数,并将该字符串添加到调用它的特定 Dog 对象的技巧数组中。

第二个方法,performTrick,也应该接受一个字符串作为参数。它应该检查该字符串是否在属于它被调用的 Dog 实例的技巧数组中;如果是这样,它应该记录字符串“名称执行技巧!”如果没有,则记录字符串“name does not Know thatrick.

我尝试将字符串推到创建的构造函数数组上,但我可能错误地使用了点表示法。

   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 arrays methods constructor prototype
2个回答
1
投票

你把事情搞得太复杂了。 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');


0
投票

您可能正在寻找的“幕后”版本(没有类方法)是这样的:

function Dog(name, breed){
  this.name=name;
  this.breed=breed;
  this.tricks=[];
}
Dog.prototype.learnTrick=function(str){
  this.tricks.push(str);
}
Dog.prototype.performTrick=function(str){
  if(this.tricks.includes(str)){
    console.log(`${this.name} performed ${str}!`);
  }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.'
© www.soinside.com 2019 - 2024. All rights reserved.