Every button displayed on your webpage is essentially an instance of the object type "HTMLButtonElement". This implies that you can interact with it just like any other object.
Imagine if, instead of a button, you had var me = {};
. You could easily set
me.state = true;
and the property would be added to the object.
Now, let's consider having two objects, var btn1 = {}, btn2 = {};
. If we assign btn1.state = true;
, only btn1
is affected even though they are instances of the same generic object type - "Object". The other object, btn2.state
, remains unaffected.
Furthermore, attempting to access a non-existent property returns the special value undefined
. In a loose comparison, this value is considered equivalent to false
(e.g., when used in if(btn2.state)
or btn2.state == false
). Thus, there is no obligation to define properties in advance as they will act as if they were set to false
.
An important point to note is that although two variables may hold different instances of the same object type (like btn1
and
btn2</code) they are not equal due to being distinct instances. For example:</p>
<pre><code>var btn1 = {}, btn2 = {};
alert(btn1 == btn2); // false
var btn1copy = btn1;
alert(btn1 == btn1copy); // true, both reference the same instance
In the above code snippet, the term "btn1copy" is misleading since it does not copy the instance but rather copies the reference. This means changes made to one variable will impact the other if they are explicitly set to be equal. For instance:
var btn1 = {}, btn2 = {}, btn1copy = btn1;
btn1copy.state = true;
alert(btn1.state); // true
alert(btn2.state); // undefined
This explanation should offer you more insight into JavaScript objects. If it has only caused further confusion, I apologize! Feel free to reach out for additional clarification.