![](/img/trans.png)
[英]Can I access the parameters of multiple objects created with object constructor function?
[英]Unable to access object created froma constructor function
這是我的問題:我有兩個輸入字段,按下按鈕后,將觸發一個函數,使用這兩個輸入值創建一個新對象(來自對象構造函數)。
函數中包含的console.log以正確的方式顯示object.input1和object.input2。 但是,一旦函數完成,我再次嘗試控制台記錄新創建的對象OR object.input1 OR object.input1,我得到'undefined'
如果我將新創建的對象推送到數組中,它沒關系,我可以從數組中訪問該對象,但不確定如何在數組內部訪問對象元素。 無論如何,我不明白在創建新對象時我做錯了什么。 任何幫助將不勝感激。
<html>
<input type="number" id='input1' placeholder="Enter number only">
<input type="text" id='input2' placeholder="Max length 300" maxlength='300'>
<button id='btn'>Submit</button>
<script>
var day1, notes1, day1List;
function DayList(day, notes) {
this.day = day;
this.notes = notes;
}
document.getElementById('btn').onclick =
function() {
var day1 = document.getElementById('input1').valueAsNumber;
var notes1 = document.getElementById('input2').value;
var day1List = new DayList(day1, notes1);
console.log(day1List.day, day1List.notes);
}
</script>
</html>
即使您在全局聲明變量:
var day1, notes1, day1List;
您沒有設置這些,因為您在函數范圍內重新聲明它們:
function() {
var day1 = document.getElementById('input1').valueAsNumber;
var notes1 = document.getElementById('input2').value;
var day1List = new DayList(day1, notes1);
}
只需刪除var聲明即可應用於全局范圍:
function() {
day1 = document.getElementById('input1').valueAsNumber;
notes1 = document.getElementById('input2').value;
day1List = new DayList(day1, notes1);
}
然而,看看你的結構,我相信你只需要將day1List作為全局變量。 其余的似乎存儲在其中。
正如fanfavorate所說,刪除double var聲明。 我還重構了你的代碼。 您通常應該使用addEventListener
而不是onclick
。 這被認為是最佳做法。
let day1, notes1, day1List; function DayList(day, notes) { this.day = day; this.notes = notes; } document.getElementById('btn').addEventListener('click', () => { day1 = document.getElementById('input1').valueAsNumber; notes1 = document.getElementById('input2').value; day1List = new DayList(day1, notes1); console.log(day1List.day, day1List.notes); })
<input type="number" id='input1' placeholder="Enter number only"> <input type="text" id='input2' placeholder="Max length 300" maxlength='300'> <button id='btn'>Submit</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.