You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS新手求助:实现Phone实例的铃声重复与更新功能

Fixing Your Custom Phone Function's Ring Repeat & Update Features

Hey there! Let's walk through what's off with your current code and fix it so it works exactly as you want.

First, let's spot the issues in your original code:

  • You set this.ring as a string in the constructor, but then try to call it like a function (samsung.ring(2)). That's why it's breaking—strings aren't callable!
  • The updateRing function isn't attached to the Phone prototype, so your htc instance can't access it. Even if it could, the logic inside is wrong (this.newRing = ring doesn't update the actual ring sound).
  • There's no logic to handle repeating the ring sound a specified number of times.

Here's the corrected code with explanations:

function Phone(ring) {
  // Store the ring sound as an instance property (we'll use a different name to avoid conflict with the method)
  this.ringSound = ring;
}

// Add the ring method to the Phone prototype so all instances can use it
Phone.prototype.ring = function(times) {
  // Create an array of 'times' length, fill it with the ring sound, then join with commas
  return Array(times).fill(this.ringSound).join(', ');
};

// Add the updateRing method to the prototype to modify the ring sound
Phone.prototype.updateRing = function(newRing) {
  // Update the instance's ringSound property with the new value
  this.ringSound = newRing;
};

// Test it out!
var samsung = new Phone('Chim');
console.log(samsung.ring(2)); // Outputs: "Chim, Chim"

var htc = new Phone('Dada');
console.log(htc.ring(3)); // Outputs: "Dada, Dada, Dada"
htc.updateRing('Riri');
console.log(htc.ring(1)); // Outputs: "Riri"

Key fixes explained:

  • We renamed the ring sound property to ringSound to avoid clashing with the ring method (since we need ring to be a function that handles repetition).
  • By attaching ring and updateRing to Phone.prototype, every instance of Phone inherits these methods—this is how prototype-based inheritance works in JS!
  • The ring method uses Array(times).fill(this.ringSound).join(', ') to quickly generate the repeated string: it creates an array of the specified length, fills it with the ring sound, then joins all elements with ", ".
  • The updateRing method simply updates the instance's ringSound property, so subsequent calls to ring() use the new sound.

内容的提问来源于stack exchange,提问作者gitdemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:37:05