这里的新手JS。我无法替换并重复该函数的值。这是代码:
function Phone(ring) {
this.ring = ring;
}
function updateRing(newRing) {
this.newRing = ring;
}
var samsung = new Phone('Chim');
samsung.ring(2); // Needs to compute to "Chim, Chim"
var htc = new Phone('Dada');
htc.ring(3); // Needs to compute to "Dada, Dada, Dada"
htc.updateRing('Riri');
htc.ring(1); // Needs to compute to "Riri"
对于第一个函数的重复值,我尝试使用 this.repeat ,但它在 Phone 函数内无效。
对于 updateRing 函数,我无法获取代码来替换 this.ring 。
我删除了我写的所有无用的代码。提前感谢您的帮助。
答案 0 :(得分:2)
您可以使用string.repeat()
let a = "ring"
console.log(a.repeat(2))
但是为了让逗号分隔符干净利落,您可以制作一次性数组,join()
使用逗号。
let ringString = Array(3).fill("ring").join(", ")
console.log(ringString)
对于其他人,您可能希望使用非常简单的类,但如果没有ployfill,则不能在IE上运行。或原型,起初可能有点混乱。这是一个使用原型在Phone
对象上定义方法的示例:
function Phone(ring) {
// changed to ring_tone too prevent clash with this.ring method
this.ring_tone = ring;
}
// you need to define these on the prototype to you can use `this`
Phone.prototype.updateRing = function(newRing) {
// don't need to define a this.newRing, just update the ring
this.ring_tone = newRing;
}
Phone.prototype.ring = function(n) {
return new Array(n).fill(this.ring_tone).join(', ')
}
var samsung = new Phone('Chim');
console.log(samsung.ring(2)); // Needs to compute to "Chim, Chim"
var htc = new Phone('Dada');
console.log(htc.ring(3)); // Needs to compute to "Dada, Dada, Dada"
htc.updateRing('Riri');
console.log(htc.ring(1)); // Needs to compute to "Riri"
答案 1 :(得分:0)
也许试试这个:
class Phone {
constructor(sound) {
this.sound = sound;
}
ring(number) {
var i;
for (i = 0; i < number; i++) {
console.log(this.sound + ", ");
}
}
updateRing(newSound) {
this.sound = newSound;
}
}
var samsung = new Phone('Chim');
samsung.ring(2);
samsung.updateRing('Riri');
samsung.ring(1);
答案 2 :(得分:0)
1)您将samsung.ring称为函数,即使它只是Phone的实例变量。
2) this.repeat 之所以不起作用的原因是因为重复不是&#34;这个&#34;&#34;这是指电话。
请改为尝试:
var samsung = new Phone('Chim');
samsung.ring.repeat(2);
var htc = new Phone('Dada');
htc.ring.repeat(3);