簡體   English   中英

向所有大寫返回的原型添加一個方法

[英]Add a method to a prototype that returns in all caps

我正在為作業編寫代碼,但我編寫的代碼在 repl.it 中出現了“語法錯誤”意外的'',即使在獲取 console.log 以輸出預期答案時,該代碼也不會讀取為 true 並顯示代碼已完成

我嘗試創建新變量並將它們同步到此並返回,但代碼讀作不正確

這就是預期的“向 Person 的原型添加一個名為“shoutName”的方法,該方法以所有大寫字母返回此人的姓名。” 這就是返回

 function Person(name) { this.name = name; this.shoutName = function() { name.toUpperCase(); return.this.name.toUpperCase(); } } /* Do not modify code below this line */ const john = new Person('John'); console.log(john.shoutName(), '<-- should be "JOHN"');

你應該刪除. return后。 而且您沒有將方法添加到prototype ,而是將方法添加到對象本身。您應該將方法添加到Person.prototype

 function Person(name){ this.name = name; } Person.prototype.shoutName = function() { return this.name.toUpperCase(); } /* Do not modify code below this line */ const john = new Person('John'); console.log(john.shoutName(), '<-- should be "JOHN"');

return關鍵字和要返回的值之間應該有一個空格,而不是一個點,這會導致SyntaxError 此外,為了更好的可維護性,您應該將shoutName方法添加到Person的原型而不是每個創建的 Person 對象。

 function Person(name) { this.name = name; } Person.prototype = { /*add any methods you want all Person objects to have*/ shoutName: function(){ return this.name.toUpperCase(); } }; const john = new Person('John'); console.log(john.shoutName(), '<-- should be "JOHN"');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM