【问题标题】:Accessing arguments from a class passed down from the constructor into a method using rest使用从构造函数传递到方法的类中的参数访问rest
【发布时间】:2022-01-18 06:02:25
【问题描述】:

我试图通过构造函数将每个参数传递到方法中,该方法反过来加密值。但是,该方法没有读取参数中的值。

请问,我做错了什么?

class Add {
    constructor(...words) {
        this.words = words;

    }

print(words){
    words = [words];
    let output = "$"
console.log(words)
    for(let word of words){
        output += word +"$"
    }
return output
}

    
}

var x = new Add("I", "Love","you");
var y = new Add("this", "is", "awesome");

x.print()
z.print()

【问题讨论】:

    标签: javascript rest class for-loop constructor


    【解决方案1】:

    您拼错了构造函数,并且如果您在构造函数内部为this 分配了某些内容,那么您还可以通过其他方法访问this 上的内容。

    class Add {
      constructor(...words) {
        this.words = words;
      }
    
      print() {
        let output = "$"
        for (let word of this.words) {
          output += word + "$"
        }
        return output
      }
    }
    
    var x = new Add("I", "Love", "you");
    console.log(x.print())

    【讨论】:

    • 我在这里输入时实际上出错了。尽快编辑。
    猜你喜欢
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多