[英]In JavaScript, why do we use el = document.createElement() to create an Element object instead of el = new Element();
That is, why do we not follow the standard JavaScript convention of using 也就是说,为什么我们不遵循标准的JavaScript使用惯例
var el = new Element("div");
but use 但是用
var el = document.createElement("div");
to do it? 去做吧?
(PS document
is an object of the class Document
. Element
is also a class, and both Document
and Element
class are defined in the browser environment). (PS
document
是类Document
的对象Element
也是一个类, Document
和Element
类都在浏览器环境中定义)。
All of the document.xxxx
methods are part of the DOM, not part of the Javascript language. 所有
document.xxxx
方法都是DOM的一部分,而不是Javascript语言的一部分。 It's a separate API that belongs to the browser, but which Javascript in the browser is allowed to access. 它是属于浏览器的单独API,但允许浏览器中的Javascript访问。
If another language were to be implemented in the browser, it would use the exact same API to access the DOM. 如果要在浏览器中实现另一种语言,它将使用完全相同的API来访问DOM。 In fact, VBScript in IE does exactly this - for proof, see some example code here .
事实上,IE中的VBScript确实如此 - 为了证明, 请参阅此处的一些示例代码 。 ( but note, I'm not recommending actually using VBScript in a browser! Stick with JS )
( 但请注意,我不建议在浏览器中实际使用VBScript!坚持使用JS )
And Javascript can be used outside of a browser environment (eg node.js), in which case it may not have or need a DOM class structure. Javascript可以在浏览器环境之外使用(例如node.js),在这种情况下,它可能没有或不需要DOM类结构。
The DOM may also be implemented outside of a browser, and the same API would be available to any languages that use use it. DOM也可以在浏览器之外实现,并且任何使用它的语言都可以使用相同的API。 For example, PHP has a DOMDocument class, which implements all the same DOM methods to add/remove/etc elements from the tree.
例如,PHP有一个DOMDocument类,它实现了所有相同的DOM方法来从树中添加/删除/ etc元素。
The way I see this is that Javascript as a language needs to be agnostic to third party control structures. 我认为这是因为Javascript作为一种语言需要与第三方控制结构无关。 In this case the DOM, adding a new element to DOM should be managed by its control object
document
not via the language new Element("div")
. 在这种情况下,向DOM添加新元素的DOM应该由其控制对象
document
管理,而不是通过语言new Element("div")
。
In node.js there is no concept of DOM elements and therefore built in DOM control would be redundant in the language. 在node.js中没有DOM元素的概念,因此在DOM控件中内置的语言将是多余的。 Abstracting the control and manipulation of the DOM within a browser therefore makes sense and should, therefore be managed by an abstracted object
document
rather than by control structures within the language. 因此,在浏览器中抽象DOM的控制和操作是有意义的,因此应该由抽象的对象
document
而不是语言中的控制结构来管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.