简体   繁体   English

Javascript:为什么classList不是Element.prototype的属性

[英]Javascript: Why is classList not a property of Element.prototype

Why is classList not a property of Element.prototype ? 为什么classList不是Element.prototype的属性? Because elements have a classList property, I would automatically assume it to be in the element's prototype , But apparently it's not. 因为元素具有classList属性,所以我会自动假定它位于元素的prototype ,但显然不是。 So where is it? 那在哪呢

Chrome's console: Chrome的控制台:

> Element.prototype.classList
undefined
> document.createElement().classList
DOMTokenList

It has to be a property of each Element instance, because if it was on the Element prototype then all elements would share the same class list, just as an Array 's .length property has to be on each array instance or all arrays would have the same length. 它必须是每个Element实例的一个属性,因为如果它在Element原型上,则所有元素将共享相同的类列表,就像Array.length属性必须在每个数组实例上或所有数组都具有相同的长度。 The point of the prototype is that it is shared by all objects of the same type. 原型的要点是,它由相同类型的所有对象共享。

In addition to nnnnnn 's answer, most instance variables are assigned in the constructor. 除了nnnnnn的答案外,大多数实例变量都在构造函数中分配。

function foo(){
    this.bar = "baz";
}

foo.prototype.bar // undefined
new foo().bar // "baz"

Functions are added to the prototype (usually, but they can also be set in the constructor). 函数被添加到原型中(通常,但是它们也可以在构造函数中设置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM