开发者

How does JavaScript distinguish between objects?

开发者 https://www.devze.com 2023-04-08 16:11 出处:网络
I have wriiten document.createElement(\"p\"); document.c开发者_运维知识库reateElement(\"p\") How does Javascript intepreter knows do distinct between those two?

I have wriiten

document.createElement("p");
document.c开发者_运维知识库reateElement("p")

How does Javascript intepreter knows do distinct between those two?

Id ? ( what is the Js property )? maybe something else ?


In this particular case:

document.createElement("p");
document.createElement("p")

the JavaScript runtime doesn't worry about the elements at all, because you didn't save the values returned. They're thrown away.

If you had written,

var p1 = document.createElementById('p');
var p2 = document.createElementById('p');

well then you've got two separate variables, and so you're keeping track of the difference.

It's important to be aware that the JavaScript interpreter itself doesn't really care too much about your DOM nodes. That's not really it's business. If you call methods and create objects, it's your problem to keep track of them.


Let's pick another real-life example: How does a human distinguish one orange from another one, in a basket? I look inside the basket, and notice that there're multiple orange-coloured, ball-shaped items

The JavaScript interpreter internally keeps track of the created objects. When an object isn't referred by anything (variables), the built-in Garbage Collector destroys the object.


It doesn't. createElement returns the object reference but if you don't assign it to anything or directly use it, it's lost.

var firstp = document.createElement("p");
var secondp = document.createElement("p");

Then you can assign an id or whatnot:

firstp.id = "first";

Keep in mind though, that this is not in the DOM yet. You have to insert it somewhere before it can be seen by the user/found with getElementById.

For that you can do something like this:

document.body.appendChild(firstp);


It doesn't. When you call document.createElement(), you create an element and it's inserted into the DOM. JavaScript can then grab certain p elements by ID, for example, or grab other p (and other) elements with getElementsByClassName().

If you'd assigned the returned values to variables, you'd be able to keep track of which one was which by referencing different variables. This is you distinguishing between them, not JavaScript, though.


You can refer to them by their index in the array of elemnts:

document.getElementsByTagName('p')[0]

You can assign id to them

document.getElementsByTagName('div')[0].id = 'first'
document.getElementsByTagName('div')[1].id = 'second'

And refer to them by id

document.getElementById('first')

It is up to you how you do it really...

0

精彩评论

暂无评论...
验证码 换一张
取 消