search
HomeWeb Front-endJS TutorialJavaScript study notes (2) Array and object part_Basic knowledge

javascript object part

1: Basic part

1. All variables in JavaScript are objects, except for two exceptions: null and undefined.

2.Jscript supports four types of objects: internal objects, generated objects, objects given by the host (all BOM and DOM objects are host objects.) and ActiveX objects (external components).

3.Microsoft Jscript provides 11 internal (or "built-in") objects. They are Array, Boolean, Date, Function, Global, Math, Number, Object, RegExp, Error, and String objects.

4. Object is just a special kind of data. Objects have properties and methods. JavaScript is an object-oriented language, but JavaScript does not use classes. JavaScript is prototype-based, not class-based.

5. Attribute: It is a variable belonging to a specific object. Method: It is a function that can only be called by a specific object.

6.Jscript object is a collection of properties and methods. A method is a function, a member of the object. A property is a value or set of values ​​(in the form of an array or object) that is a member of an object.

7.Javascript objects are based on constructor functions. When using a constructor function to create a new object, it can be said to instantiate a new object. Properties are variables inside the constructor function.

Object instantiated using constructor function:

cat = new Animal();
8.Javascript is an object-based language, and almost everything you encounter is an object. However, it is not a true object-oriented programming (OOP) language because there is no class in its syntax.

Copy code The code is as follows:



Copy code The code is as follows:
//Access the properties of the object through the period (.) or "[]"
browser.name //"Firefox"
browser["kernel"] //"Gecko"

An object (objct) is a collection of properties. Each property is composed of a "name/value pair". js also defines a special object - an array, which is an ordered list of numbered values. gather. js also defines a special object - a function. A function is an object with executable code associated with it. The code is executed by calling the function and the result of the operation is returned.

Clear the concept:
"Object-based = object-oriented" in JS 4. There is no class (Class) in JS, but it has a new name called "prototype object", so "class = prototype object"

2: The difference and connection between classes (prototype objects) and objects (instances)###  

1. Class (prototype object) is abstract and conceptual, representing a type of thing.
2. The object is specific and actual, representing a specific thing.
3. A class (prototype object) is the template of an object instance, and an object instance is an individual of the class.
A common misconception is that number literals are not objects. This is due to a bug in the JavaScript parser, which attempts to parse dot operators as part of a floating-point number literal.

There are many workarounds to make number literals look like objects.

2..toString(); // The second period can be parsed normally
2.toString(); // Pay attention to the space before the period
(2).toString(); // 2 is calculated first
Delete attribute

The only way to delete a property is to use the delete operator; setting a property to undefined or null does not actually delete the property, but only removes the association between the property and the value.

Three major features of JavaScript object-oriented

Encapsulation: Do not consider internal implementation, only consider functional usage
Inheritance: Inherit new objects from existing objects
Polymorphism: The so-called polymorphism refers to the multiple states of a reference under different circumstances,
1. Encapsulation

Encapsulation is to group the common features (including attributes and behaviors) of the same type of things into a class for ease of use. For example, people can be encapsulated in the following way:

People{
Age (Attribute 1)
Height (Attribute 2)
Gender (attribute three)

Doing something (one of the behaviors)
Walking (behavior 2)
Talking (behavior three)
}

Benefits of encapsulation:

Encapsulation protects the integrity of internal data;
Encapsulation makes object reconstruction easier;
Weaken the coupling between modules and improve the reusability of objects;
Helps avoid namespace conflicts;
Look at the following example:

Copy code The code is as follows:


This is the simplest encapsulation, encapsulating two properties into an object. However, this way of writing has two disadvantages. First, if more instances are generated, it will be very troublesome to write; second, there is no way to see the connection between the instances and the prototype.

Constructor Pattern

In order to solve the problem of generating instances from prototype objects, Javascript provides a constructor pattern.

The so-called "constructor" is actually an ordinary function, but the this variable is used internally. Using the new operator on the constructor will generate an instance, and the this variable will be bound to the instance object.

For example, the prototype objects of boy and girl can now be written like this:

Copy code The code is as follows:


We can now generate instance objects.

Copy code The code is as follows:


At this time, Boy and Girl will automatically have a constructor attribute pointing to their constructor.

Copy code The code is as follows:

alert(boy.constructor == Person); //true

alert(girl.constructor == Person); //true


Prototype mode Javascript stipulates that each constructor has a prototype attribute that points to another object. All properties and methods of this object will be inherited by the instance of the constructor.

This means that we can define those immutable properties and methods directly on the prototype object.

Copy code The code is as follows:


Then, generate the instance:

Copy code The code is as follows:


At this time, the type attribute and eat() method of all instances are actually the same memory address, pointing to the prototype object, thus improving operating efficiency.

alert(boy.eat == girl.eat); //true
The prototype property is a built-in property that specifies the constructor function that an object extends.
The following code adds a new attribute size to the Animal constructor function. This new attribute is the prototype attribute of the cat object. By using the prototype attribute, all objects that extend the Animal constructor function can access the size attribute

cat = new Animal("feline","meow", "walk/run");
cat.prototype.size = "fat";
In this case, the size attribute of all Animal objects is "fat". The prototype defaults to a new instance of Object. Since it is still an object, new properties can be added to the object. Just like style is an object of JavaScript, you can also continue to add attributes after style.

Copy code The code is as follows:


When an object is looking for an attribute, it will first traverse its own attributes. If there is none, it will continue to search for the object referenced by [[Prototype]]. If there is no more, it will continue to search for [[Prototype]].[[Prototype]. ] refers to the object, and so on, until [[Prototype]]...[[Prototype]] is undefined ([[Prototype]] of Object is undefined)

To put it simply, it saves a reference to another object through the [[Prototype]] of the object, and searches for attributes upward through this reference. This is the prototype chain.

Global window object

Any global function or variable in JavaScript is a property of window.
The self object is exactly the same as the window object. Self is usually used to confirm that it is within the current form.

The main objects of window mainly include the following:

JavaScript document object
JavaScript frames object
JavaScript history object
JavaScript location object
JavaScript navigator object
JavaScript screen object
Several common methods

valueof() method: returns the original value of the specified object
The split() method splits a string into an array of strings and returns this array.
The indexOf() method returns the first occurrence of a specified string value in a string.
The substring() method is used to extract characters between two specified subscripts in a string.
The substr() method extracts a specified number of strings starting from the startPos position from a string.
The join() method is used to put all elements in the array into a string.
arrayObject.join(separator)
The reverse() method is used to reverse the order of elements in an array.
The slice() method returns selected elements from an existing array.
Object literal

Object literals are a process used to create a large number of properties,

Copy code The code is as follows:


What needs to be noted here is that attributes and attribute values ​​are separated by colons (:); multiple attributes are separated by commas (,). Object literals can also define methods. Just write function on the attribute of the object. This is an anonymous function. To call it, you only need to write its method name ().

Copy code The code is as follows:


javascript array part

1.Array object

Array object: Provides support for creating arrays of any data type.

Copy code The code is as follows:

arrayObj = new Array()
arrayObj = new Array([size])
arrayObj = new Array([element0[, element1[, ...[, elementN]]]])

Definition: var arr = [2,3,45,6]; var arr = new Array(2,4,5,7)
There is no difference between the two definitions. [] has high performance because the code is short.

Use array and object literals: var aTest = []; When creating an array, using array literals is a good choice; similarly, object literals can also be used to save space. The following two lines are equivalent, but shorter using object literals:

var oTest = new Object; // Try not to use
var oTest = { }; //The best choice, or var 0Test = [ ];
Traversing In order to achieve the best performance when traversing an array, it is recommended to use the classic for loop.

Copy code The code is as follows:

var list = [1, 2, 3, 4, 5, ...... 100000000];
for(var i = 0, l = list.length; i console.log(list[i]);
}

The above code has a processing, which is to cache the length of the array through l = list.length.

Array constructor

Since Array's constructor is a bit ambiguous in how it handles its arguments, it is always recommended to use the literal syntax for arrays - [] - to create arrays.

So the following code will be confusing:

new Array(3, 4, 5); // Result: [3, 4, 5]
new Array(3) // Result: [], the length of this array is 3
You should try to avoid using array constructors to create new arrays. It is recommended to use the literal syntax of arrays. They are shorter and more concise, thus increasing the readability of the code.

Array array properties

Array array has three attributes: length attribute, prototype attribute, constructor attribute

1.length attribute

The Length attribute represents the length of the array, that is, the number of elements in it. Because the index of an array always starts from 0, the upper and lower limits of an array are: 0 and length-1 respectively. Unlike most other languages, the length property of JavaScript arrays is variable, which requires special attention.

2.prototype attribute

Returns a reference to the prototype of the object type. The prototype property is common to objects.

For Array array objects, the following example illustrates the use of the prototype attribute.
Add a method to the array object that returns the maximum element value in the array. To accomplish this, declare a function, add it to Array.prototype, and use it.

Copy code The code is as follows:

function array_max()
{
var i,max=this[0];
for(i=1;i {
if(max max=this[i];
}
return max;
}

Array.prototype.max=array_max;
var x=new Array(1,2,3,4,5,6);
var y=x.max();

After this code is executed, y saves the maximum value in the array x, or say 6.

3.constructor attribute

represents a function that creates an object. Description: The constructor attribute is a member of all objects with prototype. They include all JScript native objects except Global and Math objects. The constructor attribute holds a reference to the function that constructs a specific object instance.

For example:

Copy code The code is as follows:

x = new String("Hi");
if(x.constructor==String) //Process (condition is true).
//or
function MyFunc{
//Function body.
}

y=new MyFunc;
if(y.constructor==MyFunc)//Processing (condition is true).


For arrays:

y = new Array();

Array method:

Attached is a mind map of the array:

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool