I want to know for what reason the programme is working in the second case but not in the first one.
CASE1:-
let tem=document.getElementById('timed').value
let timeBtn=document.getElementById('timed_input');
timeBtn.addEventListener('click',()=>{
console.log(tem);
})
开发者_开发百科
CASE2:-
let timeBtn=document.getElementById('timed_input');
timeBtn.addEventListener('click',()=>{
console.log(document.getElementById('timed').value);
})
Because value is very likely to be a primitive data type. When you assign a primitive value to a variable, the value is copied to the variable. In contrast, when you assign an object to a variable, you get a reference of the object and not a copy of it.
Take a look at this example.
let a = 20;
let b = a;
a = 30;
console.log(a); // 30
console.log(b); // 20
Even though we assign let b = a
, we stored the value of a (20) into b, b and a don't have a relation to each other.
In contrast with non primitive data types, like objects:
let a = { name: "Doria", age: 22 };
let b = a;
b.name = "Nicole";
console.log(a.name); // Nicole
console.log(b.name); // Nicole
In this case, a and b are related, in the sense that they are referencing the same object.
精彩评论