出于學習目的,我創建了一個 JS 檔案。我在 JS-Object 中實作了一個方法來獲取 BookStorage 計數器。問題是每次我添加書籍時,瀏覽器都會給我回傳物件的默認值。有人有想法嗎?
這是我的代碼的一些片段:
書級:
class Book{
constructor(
name,
quantity
){
this.name = name,
this.quantity = quantity
}
showStorage(param) {
if(param != null){
return this.quantity param;
this.quantity = param;
}
else {return this.quantity;}
}
}
主腳本:
import Book from "./Book.js"
const lordOfRings = new Book(
"Lord of the Rings",
10
)
console.log("The Book:", lordOfRings.name);
console.log("The number in Storage:", lordOfRings.showStorage());
console.log("Adding 10 Books to storage:", lordOfRings.showStorage(10));
console.log("Adding 10 Books to storage:", lordOfRings.showStorage());
console.log("New Storage amount of Books:", lordOfRings.showStorage(10));
我的預期輸出是:
"Lord of the Rings"
10
20
20
30
而不是我得到:
"Lord of the Rings"
10
20
10
20
uj5u.com熱心網友回復:
問題是因為在函式中,return
應該是最后一行。
return 陳述句結束函式執行并指定要回傳給函式呼叫者的值。(MDN 檔案)
由于函式執行結束,這意味著return
陳述句之后的代碼永遠不會執行。
我建議使用代碼執行可視化工具除錯您的代碼
這是您的代碼的一部分。您試圖更改陳述句this.quantity
后的值。return
showStorage(param) {
if(param != null){
return this.quantity param; // This doesn't change the value of this.quantity. It just returns that value 10 (in your example). The value of `this.quantity` is always the same.
// This line does not run because it's after the return statement
this.quantity = param;
}
else {return this.quantity;}
}
}
這是一個最小的修復。您需要增加 的值this.quantity
,然后回傳它。
showStorage(param) {
if(param != null){
this.quantity = param;
return this.quantity;
}
else {return this.quantity;}
}
}
這是考慮到Ivar 評論的重構
showStorage(param) {
if(param != null){
this.quantity = param;
}
return this.quantity;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495687.html
標籤:javascript 变量 方法
上一篇:提交按鈕不適用于JS驗證