web06. Advanced knowledge of JavaScript

Posted by tecdesign on Sun, 02 Jan 2022 21:46:10 +0100

Prototype object

Prototype object

Each function will be given a prototype attribute when it is created, which points to the prototype object of the function. This object can contain the attributes and functions shared by all instances. Therefore, after using the prototype attribute, the attributes and functions shared by the instances can be extracted from the constructor function and added to the prototype attribute.

function Person(name, age) {
    this.name = name;
    this.age = age;
}
Person.prototype.sayName = function () {
    console.log(this.name);
};
var person1 = new Person();
var person2 = new Person();
console.log(person1.sayName === person2.sayName);

The sayName() function shared by the instance is added to person On the prototype attribute, through testing, we will find that the * * sayName attribute in different instances is equal * *.

Using the prototype attribute solves the problem that simply creating an instance through the constructor will cause the function to be created repeatedly in different instances.

Prototype objects, constructors, and instances

The prototype property of the constructor will point to its prototype object, and the concrete instance can be generated through the constructor

Prototype object:

  1. Prototype object, constructor and instance relationship?

    Each constructor has a prototype object. The prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. Generally speaking, the instance can access the prototype object through the internal pointer, and the prototype object can find the constructor through the constructor

  2. After creating an instance of an object using a prototype object, what is the order in which the properties of the instance are read?

    The instance object must be created after the prototype object

  3. If the prototype object is rewritten, what problems will it bring?

    When you rewrite the prototype object, its constructor property disappears Usually we will remake the 'constructor' attribute, and the inheritance relationship between objects is actually__ proto__ And The relationship between prototypes

Relationship between prototype object, constructor and instance

  1. Each function will be given a prototype attribute when it is created, which points to the prototype object of the function. By default, all prototype objects will add a constructor attribute to point to the function where the prototype attribute is located, that is, the constructor.
  2. When the constructor is called through the new operator to create an instance, the instance has a__ proto__ Property that points to the prototype object of the constructor, so__ proto__ Property can be seen as a bridge between the instance and the prototype object of the constructor.
function Person() {}
Person.prototype.name = 'cao teacher';
Person.prototype.age = 29;
Person.prototype.job = 'code teacher';
Person.prototype.sayName = function () {
    console.log(this.name);
};
var person1 = new Person();
var person2 = new Person();
console.log(person1.sayName === person2.sayName);//true

Take the above example to see the relationship between prototype objects and instances

  1. The constructor Person has a prototype attribute, which points to the prototype object of Person. In the prototype object, there are the constructor attribute and the attributes on the other four prototype objects, in which the construct attribute points to the constructor itself.
  2. The two instances of person1 and person2 created by the new operator have one__ proto__ Property points to the Person prototype object.

The order in which the properties of the instance are read

When we read a property through an instance of an object, there is a search process. It will first find the specified property in the instance itself. If it is found, it will directly return the value of the property. If it is not found, it will continue to look along the prototype object. If it is found in the prototype object, it will return the value of the property.

According to the previous example, suppose we need to output person1 For the name attribute, you will find the name attribute in the person1 instance itself, but person1 itself does not have this attribute, so you will continue to search along the prototype object. You will find the name attribute value "cao teacher" on the prototype object, so you will finally output "cao teacher".

function Person() {
    this.name = 'caoteacher';
}
Person.prototype.name = 'cao teacher2';
Person.prototype.age = 29;
Person.prototype.job = 'code teacher';
Person.prototype.sayName = function () {
    console.log(this.name);
};
var person1 = new Person();
console.log(person1.name);//caoteacher

We added a name attribute in the Person() constructor, which is an instance attribute when we need to output person1 For the name attribute, you will first look for the name attribute in the person1 instance itself. You can find that the attribute value is' cao teacher ', so you output' cao teacher '.

Similarly, if the Person() constructor has both the instance attribute with the same name and the attribute on the prototype object, and the instance attribute of the instance is deleted after the instance is generated, the value of the attribute on the prototype object will be output.

function Person() {
    //The name here is the instance attribute
    this.name = 'caoteacher';
}
//The name here is the attribute on the prototype object
Person.prototype.name = 'cao teacher2';
var person1 = new Person();
//Delete the properties of the instance
delete person1.name;
console.log(person1.name);//cao teacher2

Override prototype object

Every time you add a property or function to the prototype object, you need to manually write person Prototype, which is a redundant writing method. We can write all the attributes that need to be bound to the prototype object in the form of an object literal and assign it to prototype.

function Person() {}
Person.prototype = {
    constructor: Person,
    //important
    name: 'cao teacher2',
    age: 29,
    job: 'code teacher',
    sayName: function () {
        console.log(this.name);
    }
};

When we create an instance of the person object, we can still normally access the properties on each prototype object.

Assigning an Object literal to the prototype attribute actually rewrites the prototype Object, which is equivalent to cutting off the relationship between the constructor and the original prototype. Therefore, it should be noted that if you still want to use the constructor attribute for subsequent processing, you should add a constructor attribute to the Object literal to point to the constructor itself, Otherwise, the constructor property of the prototype will point to the constructor of Object type, resulting in the separation of the constructor property from the constructor. As follows.

function Person() {}
Person.prototype = {
    name: 'cao teacher2',
    sayName: function () {
        console.log(this.name);
    }
}
console.log(Person.prototype.constructor === Object);//true
console.log(Person.prototype.constructor === Person);//false

Prototype chain

Prototype chain

Each instance of an object has a__ proto__ Property refers to the prototype object of the constructor, and the prototype object also has a__ proto__ Property points to the prototype object of the upper constructor, so it goes up layer by layer until a prototype object at the top is null. In JavaScript, almost all objects have__ proto__ Properties, by__ proto__ The link formed by attribute linking constitutes the prototype chain of JavaScript, and the top of the prototype chain is object Prototype, his__ proto__ Property is null.

Characteristics of prototype chain

  1. Due to the existence of prototype chain, the process of attribute search is no longer to only find its own prototype object, but will go up along the whole prototype chain until it can be traced back to object Prototype, if object If the attribute cannot be found on the prototype, it will return undefined. If the attribute is found on the instance itself or a prototype object during the period, the result will be returned directly. Therefore, there will be the problem of attribute coverage. Due to the existence of feature 1, we can also call some functions that are not on the defined constructor when generating the instance of the defined object, For example, toString() function.
function Person(){}
var p = new Person();
p.toString();
//Object actually calls object prototype. Tostring() function
  1. Because attribute lookup will go through the whole prototype chain, the longer the lookup link, the greater the impact on performance.

Attribute differentiation

How to distinguish whether the attribute is inherited from the instance itself or from the prototype chain?

The prototype object of the Object() constructor provides a hasOwnProperty() function to determine whether the property is owned by itself.

function Person(name) {
    //Instance property name
    this.name = name;
}
//Properties on prototype objects
Person.prototype.age = 12;
var person = new Person('cao teacher');
console.log(person.hasOwnProperty('name'));//true
console.log(person.hasOwnProperty('age'));//false

Built in constructor

There are some specific built-in constructors in javaScript, such as String() function, Number() constructor, Array() constructor, Object() constructor, etc. Their own__ proto__ Properties all point to function prototype

console.log(String.__proto__ === Function.prototype);//true
console.log(Number.__proto__ === Function.prototype);//true
console.log(Array.__proto__ === Function.prototype);//true
console.log(Object.__proto__ === Function.prototype);//true
console.log(Date.__proto__ === Function.prototype);//true
console.log(Function.__proto__ === Function.prototype);//true

__ proto__ attribute

In the prototype chain system of JavaScript, the most important is__ proto__ Property, which is the only way to connect prototype chains in series.

var str = new String('cao teacher');
console.log(str);

The value of STR contains 10 characters and a length attribute. But when we call str.substring(1,3), we don't report an error. Why? Because__ proto__ Property can be found along the prototype chain Function in prototype, and substring() function is in it.

Function.prototype.a='a';
Object.prototype.b='b';
function Person(){}
var p = new Person;
console.log('p.a',p.a);//p.a undefined
console.log('p.b',p.b)//p.b b
//Prototype chain of instance p
P.__proto__ = Person.prototype;
//Prototype of Person prototype object
Person.prototype.__proto__ = Object.prototype;

inherit

Inheritance is one of the three characteristics of object-oriented language. The three characteristics are (inheritance, encapsulation and polymorphism). It can make subclass objects have the characteristics of parent objects without affecting the implementation of parent objects. At the same time, it can also expand the unique characteristics of subclass objects without affecting the behavior of parent objects, which brings great convenience to coding.

Although JavaScript is not an object-oriented language and does not have the characteristics of inheritance directly, we can realize inheritance indirectly in some ways, so as to take advantage of inheritance and enhance code reusability and expansibility.

//Define a parent class Animal
function Animal(name){
	//attribute
	this.type = 'Animal';
	this.name = name || 'animal';
	//Instance function
	this.sleep = function(){
		console.log(this.name+'be sleeping');
	}
}
//Prototype function
Animal.prototype.eat = function(food){
	console.log(this.name + 'I am eating:'+food);
}

Prototype chain inheritance

The main idea is to rewrite the prototype attribute of the subclass and point it to the instance of the parent class.

Define a subclass Cat, which is used to inherit the parent class Animal

//Subclass Cat
function Cat(name) {
    this.name = name;
}
//Prototype inheritance
Cat.prototype = new Animal();
//The key sentence is to point Cat's constructor to itself
Cat.prototype.constructor = Cat;
var cat = new Cat('Garfield');
console.log(cat.type);
console.log(cat.name);
console.log(cat.sleep());
console.log(cat.eat('Cat food'));

In the subclass Cat, we do not add the type attribute, so we will directly inherit the type attribute of the parent class Animal and output the string 'Animal'.

In the subclass Cat, we added the name attribute. When claiming an instance of the subclass Cat, the name attribute value will overwrite the name attribute value of the parent Animal. Therefore, the string "Garfield Cat" will be output instead of the name attribute "Animal" of the parent Animal.

Because the prototype attribute of cat points to the instance of Animal type, when generating the instance cat, it will inherit the instance function and prototype function. When calling the sleep() function and eat() function, this points to the instance cat, thus outputting "Garfield is sleeping!" and "Garfield is eating cat food".

//A key sentence is to point cat's constructor to itself prototype. constructor = Cat;

Because if you do not point the constructor property of the Cat prototype object to its own constructor, it will point to the constructor of the parent class Animal.

Advantages and disadvantages of prototype chain inheritance

Advantages of prototype chain inheritance

  1. Simple and easy to implement

    You only need to set the prototype attribute of the subclass as the instance of the parent class, which is simple to implement.

  2. Inheritance is pure

    The generated instance is an instance of both the child class and the parent class.

  3. You can directly access parent prototype chain properties and functions through subclasses

    Through the subclasses inherited from the prototype chain, you can directly access the new functions and properties on the parent prototype chain. Continuing with the previous code, we test by adding properties and functions to the prototype chain of the parent class

//Add attribute on parent prototype chain
Animal.prototype.bodyType = 'small';
//Add function to parent prototype chain
Animal.prototype.run = function () {
    return this.name + 'Running';
};
//Result verification
console.log(cat.bodyType);
console.log(cat.run());

Disadvantages of prototype chain inheritance

  1. All instances of the subclass will share the properties of the parent class

    When prototype chain inheritance is used, the prototype attribute of the subclass Cat is directly rewritten and pointed to an instance of Animal. Then all instances that generate Cat objects will share the attributes of the instance of Animal.

    //Generate an instance of animal
    var animal = new Animal();
    //By changing the prototype chain of Cat, all Cat instances will share the attributes in animal
    Cat.prototype = animal;
    
  2. When creating a subclass implementation, you cannot pass parameters to the constructor of the parent class

    When creating an instance of a subclass through the new operator, the constructor of the subclass will be called, but the association with the parent class is not set in the constructor of the subclass, so the parameters cannot be passed to the constructor of the parent class.

  3. Cannot implement multiple inheritance

    Since the prototype attribute of the subclass Cat can only be set to one value, if it is set to multiple values at the same time, the latter value will overwrite the previous value, resulting in Cat inheriting only one parent class and cannot realize multiple inheritance.

  4. When adding properties and functions on prototype objects to subclasses, they must be placed after the new Animal() function, because if the prototype property is set before this statement, the subsequent statements will directly override the prototype property, resulting in all previous settings invalid.

Cat.prototype = new Animal();

Construction inheritance

Construction inheritance

The main idea of constructing inheritance is to change the direction of this through the call() function in the constructor of the subclass and call the constructor of the parent class, so that the properties and functions of the instance of the parent class can be bound to this of the subclass.

//Define a parent class Animal
function Animal(age) {
    //attribute
    this.name = 'Animal';
    this.age = age;
    //Instance function
    this.sleep = function () {
        console.log(this.name + 'be sleeping');
    }
}
//Parent prototype function
Animal.prototype.eat = function (food) {
    return this.name + 'I am eating' + food;
};
//Subclass
function Cat(name) {
    //The core implements the inheritance of the attributes and functions of the instance of Animal through the call() function
    Animal.call(this);
    this.name = name || 'Tom';
}
//Generate instances of subclasses
var cat = new Cat('tony');
//The parent class instance function can be called normally
cat.sleep();
//Cannot call parent prototype function
cat.eat();

Subclasses can normally call the instance function of the parent class, but cannot call the function on the prototype object of the parent class. This is because subclasses do not call the function on the prototype object of the parent class in some way.

Advantages and disadvantages of constructive inheritance

Advantages of constructive inheritance

  1. It can solve the problem that subclass instances share parent class properties.

    The call() function actually changes the direction of this in the Animal constructor of the parent class. After calling, this points to the subclass Cat, which is equivalent to that the type, age, sleep and other attributes and functions of the parent class are directly bound to this of the subclass and become the attributes and functions of the subclass instance. Therefore, the generated subclass instances have their own type, age and sleep attributes and functions, Will not affect each other.

  2. When you create an instance of a subclass, you can pass parameters to the parent class

    //Define a parent class Animal
    function Animal(age) {
        //attribute
        this.name = 'Animal';
        this.age = age;
        //Instance function
        this.sleep = function () {
            console.log(this.name + 'be sleeping');
        }
    }
    //Parent prototype function
    Animal.prototype.eat = function (food) {
        return this.name + 'I am eating' + food;
    };
    //Subclass
    function Cat(name, parentAge) {
        //When a subclass generates an instance, it passes parameters to the call() function, indirectly to the parent class, and then inherited by the subclass
        Animal.call(this, parentAge);
        this.name = name || 'Tom';
    }
    //Generate instances of subclasses
    var cat = new Cat('tony', 11);
    //The parent class instance function can be called normally
    console.log(cat.age);//11
    
  3. Multiple inheritance can be implemented

    The call() function is called several times to inherit multiple parent objects. Each call() function will bind the properties and functions of the instance of the parent class to this of the child class.

Disadvantages of constructing inheritance

  1. An instance is only an instance of a subclass, not an instance of a parent class.

Reason: because we did not concatenate the subclass with the parent class through the prototype object, the generated instance has no relationship with the parent class, thus losing the significance of inheritance.

  1. Only the properties and functions of the parent class instance can be inherited, and the properties and functions on the prototype object cannot be inherited.

  2. Cannot reuse instance functions of a parent class

    Since the instance function of the parent class will be bound to this of the child class through the call() function, each instance generated by the child class will have a reference to the instance function of the parent class, which will cause unnecessary memory consumption and affect performance.

Copy inheritance

Main ideas:

  1. First, an instance of the parent class is generated
  2. Then traverse the properties and functions of the parent class instance through for... in
  3. And set it as the property and function of the subclass instance or the property and function on the prototype object in turn.
//Define a parent class Animal
function Animal(parentAge) {
    //Instance properties
    this.name = 'Animal';
    this.age = parentAge;
    //Instance function
    this.sleep = function () {
        console.log(this.name + 'be sleeping');
    }
}
//Prototype function
Animal.prototype.eat = function (food) {
    return this.name + 'I am eating' + food;
};
//Subclass
function Cat(name, age) {
    var animal = new Animal(age);
    //The properties and functions of the parent class are added to the child class
    for (var key in animal) {
        //Instance properties and functions
        if (animal.hasOwnProperty(key)) {
            this[key] = animal[key];
        } else {
            //Properties and functions on prototype objects
            Cat.prototype[key] = animal[key];
        }
    }
    //Properties of the subclass itself
    this.name = name;
}
//Subclass self prototype function
Cat.prototype.eat = function (food) {
    return this.name + 'I am eating:' + food;
}
var cat = new Cat('tony', 12);
console.log(cat.age);
cat.sleep();
console.log(cat.eat('Cat food'));
  1. animal.hasOwnProperty(key) returns "true", which means it is the property and function of the instance. It is directly bound to this of the subclass and becomes the property and function of the subclass instance

  2. animal.hasOwnProperty(key) returns "false", which means it is a property and function on the prototype object. It is added to the prototype property of the subclass to become the property and function on the prototype object of the subclass.

  3. The generated subclass instance cat can access the inherited age attribute, and can also call the inherited sleep() function and eat() function on its prototype object.

Advantages and disadvantages of replication inheritance

Advantages of replication inheritance

  1. Support multiple inheritance

    You only need to generate multiple instances of the parent class in the constructor of the child class, and then process them through the same for... In

  2. It can inherit the properties and functions of the instance and the properties and functions on the prototype object at the same time

    When all properties are processed for... in, it will judge whether they are the properties and functions of the instance or the properties and functions of the prototype object through the hasOwnProperty() function, and make different settings according to the results, so as to inherit both the properties and functions of the instance and the properties and functions of the prototype object

  3. You can pass values to the parent class constructor

    When generating an instance of a subclass, you can pass the attribute value of the parent class in the constructor, and then directly pass the value to the constructor of the parent class in the subclass constructor.

Disadvantages of replication inheritance

  1. All properties of the parent class need to be copied, which consumes memory.

    All attributes of the parent class need to be copied again, which will cause memory reuse and reduce performance.

  2. An instance is only an instance of a subclass, not an instance of a parent class

    In fact, we only traverse the properties and functions of the parent class and copy them to the child class. We do not connect the parent class and child class through the prototype object. Therefore, the instance of the child class is not the instance of the parent class.

Combinatorial inheritance

Combinatorial inheritance

Main ideas:

  1. Two methods of construction inheritance and prototype inheritance are combined
  2. On the one hand, in the constructor of the subclass, call the constructor of the parent class through the call() function to bind the properties and functions of the instance of the parent class to this of the subclass,
  3. On the other hand, by changing the prototype attribute of the subclass, it inherits the attributes and functions on the prototype object of the parent class.
//Define a parent class Animal
function Animal(parentAge) {
    //Instance properties
    this.name = 'Animal';
    this.age = parentAge;
    //Instance function
    this.sleep = function () {
        console.log(this.name + 'be sleeping');
    };
    this.feature = ['fat', 'thin', 'tall'];
}
//Prototype function
Animal.prototype.eat = function (food) {
    return this.name + 'I am eating:' + food;
};
//Subclass
function Cat(name) {
    //Inherit the properties and functions of the instance through the constructor
    Animal.call(this);
    this.name = name;
}
//Inherit properties and functions on prototype objects through prototypes
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat = new Cat('tony');
console.log(cat.name);
cat.sleep();
console.log(cat.eat("Cat food"));

Advantages and disadvantages of composite inheritance

Advantages of combinatorial inheritance

  1. It can inherit the properties and functions of both the parent class instance and the prototype object

    Via animal Call (this) can bind the properties and functions of the parent class instance to this of the Cat constructor. On the other hand, through Cat Prototype = new animal can bind the properties and functions on the prototype object of the parent class to the Cat prototype object.

  2. It is both an instance of a child class and an instance of a parent class

  3. There is no reference property sharing problem

    Because the instance property of the parent class has been pointed to this of the child class in the constructor of the child class, even if the instance property of the parent class is bound to the prototype property of the child class later, there will be no problem of reference property sharing because the scope priority of the constructor is higher than that of the prototype chain

  4. You can pass parameters to the constructor of the parent class

    You can pass parameters to the constructor of the parent class through the call() function.

Disadvantages of combinatorial inheritance

The disadvantage of composite inheritance is that the instance property of the parent class will be bound twice

(in the constructor of the subclass, the constructor of the parent class is called once through the call() function. When rewriting the prototype attribute of the subclass and generating an instance of the parent class, the constructor of the parent class is called once.)

Parasitic combinatorial inheritance

Parasitic combinatorial inheritance

When setting the prototype property of a subclass, you can remove the properties and functions of the parent class instance.

//Define a parent class Animal
function Animal(parentAge) {
    //Instance properties
    this.name = 'Animal';
    this.age = parentAge;
    //Instance function
    this.sleep = function () {
        console.log(this.name + 'be sleeping');
    };
    this.feature = ['fat', 'thin', 'tall'];
}
//Prototype function
Animal.prototype.eat = function (food) {
    return this.name + 'I am eating:' + food;
};
//Subclass
function Cat(name) {
    //Inherit the instance properties and functions of the parent class
    Animal.call(this);
    this.name = name;
}
//Execute function now
(function () {
    //Set any function Super()
    var Super = function () {};
    //The prototype of the key statement Super() function points to the prototype of the parent class Animal, and the instance attribute of the parent class is removed
    Super.prototype = Animal.prototype;
    Cat.prototype = new Super();
    Cat.prototype.constructor = Cat;
})();
var cat = new Cat('tony');
console.log(cat.name);
console.log(cat.sleep());
console.log(cat.eat("Cat food"));

Object type and its instances and static functions

new operator in JavaScript

Since instances of reference data types need to be generated through the new operator, we need to understand the relevant knowledge of the new operator. The new operator will change the direction of this during execution, so before understanding the new operator, let's first understand the usage of this.

function Cat(name,age){
    console.log(this);
    this.name = name;
    this.age = age;
}
new Cat('miaomiao',18);


function Cat(name,age){
    var Cat = {};
    Cat.name = name;
    Cat.age = age;
    return Cat;
}
console.log(new Cat('miaomiao',18));

The actual value of this is the empty object of Cat. The last two sentences are equivalent to adding the name and age attributes to the Cat object

If the function has no return value, it defaults to return this. This in the above code is actually an empty Cat object, and the name and age attributes are only added to the temporary variable Cat. In order to make the output include the name and age attributes, we just return the temporary variable Cat

You do three things with the new operator

var cat = {};
cat.__proto__ = Cat.prototype;
Cat.call(cat);

HTMLCollection object and NodeList object

HTMLCollection object

It mainly calls the children attribute and the childNodes attribute.

<div id="main">
    <p class="first">first</p>
    <p class="second">second<span>content</span></p>
</div>
<script>
var main = document.getElementById('main');
console.log(main.children);
console.log(main.childNodes);

The HTMLCollection object has the length attribute, which returns the length of the collection. You can access specific elements through the item() function and the namedItem() function.

item() function

The HTMLCollection object can call the Item() function to obtain a specific node through the sequence number. If it exceeds the index, it will return "null".

<div id="main">
    <p class="first">first</p>
    <p class="second">second</p>
    <p class="three">three</p>
    <p class="four">four</p>
</div>
<script>
    var main = document.getElementById('main').children;
    console.log(main.item(0));//<p class="first">first</p>
    console.log(main.item(2));//<p class="three">three</p>
</script>

namedIrem() function

The namedIrem() function is used to return a node. First, match it through the id attribute. If it does not match, use the name attribute. If it does not match, return "null". When there is a duplicate id or name attribute, only the first matching value is returned.

<form id="main">
    <input type="text" id="username">
    <input type="text" name="username">
    <input type="text" name="password">
</form>
<script>
    var main = document.getElementById('main').children;
    console.log(main.namedItem('username'));
</script>

NodeList object

The NodeList object also has the length attribute, returns the length of the collection, and also has the item() function, which is the same as the effect in the HTMLCollection object.

The HTMLCollection object and NodeList object are not static snapshots of the status of historical documents, but are real-time. Adding or deleting a related node in the DOM tree will immediately be reflected in the HTMLCollection object and NodeList object.

Similarities and differences between HTMLCollection and NodeList

Same point

  1. They are array like objects with a length attribute. They can be obtained through the call function and processed into a real array by the apply function.
  2. Both have an item() function to locate elements by index.
  3. Are real-time.

difference

  1. HTMLCollection has one more namedItem() function than NodeList.
  2. The HTMLCollection object contains only a collection of elements, that is, elements with tag names, while the NodeList object is a collection of nodes, that is, elements and nodes.
    text" name="username">
```

NodeList object

The NodeList object also has the length attribute, returns the length of the collection, and also has the item() function, which is the same as the effect in the HTMLCollection object.

The HTMLCollection object and NodeList object are not static snapshots of the status of historical documents, but are real-time. Adding or deleting a related node in the DOM tree will immediately be reflected in the HTMLCollection object and NodeList object.

Similarities and differences between HTMLCollection and NodeList

Same point

  1. They are array like objects with a length attribute. They can be obtained through the call function and processed into a real array by the apply function.
  2. Both have an item() function to locate elements by index.
  3. Are real-time.

difference

  1. HTMLCollection has one more namedItem() function than NodeList.
  2. The HTMLCollection object contains only a collection of elements, that is, elements with tag names, while the NodeList object is a collection of nodes, that is, elements and nodes.

Topics: Javascript