Home Web Front-end JS Tutorial Detailed explanation of issues related to JavaScript variables

Detailed explanation of issues related to JavaScript variables

Mar 26, 2017 pm 05:02 PM

This article focuses on the difference between two different data types contained in JavaScript variables-basic type values ​​and reference type values. In addition, I briefly touched on the relationship between ECMAScript and JavaScript.

The title is JavaScript variables, but more specifically it should be ECMAScript variables.

In the 1990s, Netscape and Microsoft launched two different versions of JavaScript, which was not conducive to the development and use of JavaScript, prompting the European Computer Manufacturers Association (ECMA, The European Computer Manufacturers Association began to deal with the standardization of JavaScript, thus completing the famous ECMA-262 - a standard that defines a new scripting language called ECMAScript.

A complete JavaScript implementation includes ECMAScript, Document Object Model (DOM, Document Object Model), and Browser Object Model (BOM, Browser Object Model). ECMAScript, as the core and implementation basis of JavaScript, is a description of the language in terms of syntax, types, statements, keywords, reserved words, operators and objects specified by the ECMA-262 standard.

ECMAScript variables specified in the ECMA-262 standard are loosely typed and can be used to save any type of data, so the operations of initializing variables of different types can be placed in one statement It is legal to execute the following code.

 var message = "hello",  //string     
 age = 20,           //number3     
 found = false;   //boolean 
Copy after login

  A variable defined with the var operator will become a local variable in the scope in which the variable is defined. The variable will be destroyed immediately after exiting the scope. For example, if you define a variable within a function, the variable is created when the function is called, but after the function exits, the variable can no longer be accessed.

There are 6 data types in ECMAScript (only 6, ECMAScript does not support any mechanism for creating custom types).

The basic data types include 5 types - underfined, null, boolean, number, string. These 5 basic data types are accessed by value, and their values ​​belong to the basic data types mentioned at the beginning of the article. Type values ​​are simple data segments that can manipulate the actual value stored in the variable.

The sixth type is the complex data type - object, which is essentially composed of a set of unordered name-value pairs. It is a reference type value and is stored in memory. object. JavaScript does not allow direct manipulation of the memory space of an object. When operating an object, you are actually operating a reference to the object rather than the actual object.

Although it is not necessary to specify what data type a variable is when defining it, the operations that can be performed on the values ​​of basic types and reference types are still very different.

 Adding attributes

For reference type values, you can add attributes and Methods to add, change and delete, as shown in the following code:

var obj = new object();  //创建对象并保存在obj中
obj.name = "Marry";      //添加名为name的属性,赋予字符串值“Marry”
alert(obj.name);         //弹出"Marry"
Copy after login

If the obj object is not destroyed or the name attribute is not deleted, this attribute will always exist.

Look at the basic type value again:

var name = "Marry";  //创建字符串
name.age = 20;       //添加名为age的属性,赋予number值20
alert(name.age);     //弹出"underfined"
Copy after login

The name string has an age attribute added to it and is assigned a value of 20, but it will be accessed next time This attribute will disappear.

This means that attributes can only be added dynamically to reference type values.

 Copy variable value

 From variable a Copying the basic type value to variable b will create a new value on the variable b object and copy the value to the location assigned to variable a , saved independently. Any operations involving these two variables will not affect each other.

  若从变量c变量d复制引用类型的值,同样会将存储在变量d对象中的值复制一份放到为变量c分配的空间中,但这个值的副本实际是一个指针,与变量d指向堆内存中的同一个对象。两个变量实际引用同一个对象,改变其中一个变量,将影响另一个变量。

  具体区别见如下例子:

//基本类型值
var num1 = 5;var num2 = num1;
num2 = num2 + 5;
alert(num1);                   
//5alert(num2);                   
//10/
/引用类型值
var obj1 = new object();var obj2 = obj1;
obj1.name = "Marry";
alert(obj2.name);            
//"Marry"
Copy after login

  函数传参

  ECMAScript中所有函数的参数都是按值传递的,即将函数外部的值复制给函数内部的参数。鉴于基本类型值与引用类型值复制变量的不同,其函数传参的效果也不同。

  在向参数传递基本类型值时,被传递的参数被赋给一个局部变量,函数内部参数的变化不影响函数外部的变量;向参数传递引用类型值时,会把这个值在内存中的地址复制给一个局部变量,因此这个局部变量的变化将会反映在函数的外部。如下列例子:

//传递基本类型值function addnum(num) {
    num += 10;    return num; 
}var num1 = 5;var num2 = addnum(num1);
alert(num1);                  
//5,无变化alert(num2);                  
//15//传递引用类型值
function setage(obj) {
    obj.age = 20;
}var obj1 = new object();
setage(obj1)
alert(obj1.age);            //20
Copy after login

在局部作用域中修改的对象反映在全局作用域中,很多人会以为这是按引用传递。但函数对象确实都是按值传递,见下列例子:

function setage(obj) {
    obj.age = 20;
    obj = new object();
    obj.age = 30;
}var obj1 = new object();
setage(obj1)
alert(obj1.age);           
//20
Copy after login

  此例中在函数内部为obj重新定义了一个对象,且为其age属性重新赋值,但这一变化并未反映在函数外部,说明obj1 并不是按引用传递的。实际函数内重新定义的对象为局部对象,在退出函数后就会被立即销毁。

  检测类型

  基本类型值可以通过typeof检测,但typeof检测引用类型时只能返回object。所以为了知道某个值是什么类型的对象,ECMAScript提供了instanceof操作符,语法如下:

result = variable instanceof constructor
Copy after login

如果变量是引用类型的实例,instanceof操作符就会返回true。

The above is the detailed content of Detailed explanation of issues related to JavaScript variables. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Mind map of Python syntax: in-depth understanding of code structure Mind map of Python syntax: in-depth understanding of code structure Feb 21, 2024 am 09:00 AM

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

What are instance variables in Java What are instance variables in Java Feb 19, 2024 pm 07:55 PM

Instance variables in Java refer to variables defined in the class, not in the method or constructor. Instance variables are also called member variables. Each instance of a class has its own copy of the instance variable. Instance variables are initialized during object creation, and their state is saved and maintained throughout the object's lifetime. Instance variable definitions are usually placed at the top of the class and can be declared with any access modifier, which can be public, private, protected, or the default access modifier. It depends on what we want this to be

Deep understanding of const in C language Deep understanding of const in C language Feb 18, 2024 pm 12:56 PM

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint

See all articles