Home Web Front-end JS Tutorial How variables are stored in JavaScript

How variables are stored in JavaScript

Nov 22, 2016 pm 02:39 PM
javascript variable

Basic Principle

In js, variables include 5 basic types and a complex data type Object. Of course, commonly used functions and arrays are all objects. For basic types and complex types, there are two different storage methods - stack storage and heap storage. The reason why two storage methods are implemented is very simple, that is, once the basic type is initialized, the memory size is fixed, and accessing the variable means accessing the actual data in the memory of the variable, which is called access by value. The object type may increase its size at some point, and the memory size is not fixed. For example, dynamically adding attributes of objects, dynamically increasing the size of arrays, etc. will increase the size of variables and cannot be maintained on the stack. Therefore, js puts the object type variables into the heap, allowing the interpreter to allocate memory for it as needed, and access it through the reference pointer of the object. Because the memory address size of the object in the heap is fixed, it can be The memory address is stored in a reference to stack memory. This method is called access by reference. Well, it is important to understand this and you can avoid a lot of problems in future programming. Let’s take a look at the following code:

var a = 'I am a string.';   //a,b,c的变量中保存的都是实际的值,因为他们是基本类型的变量
var b = 1010;
var c = false;
var d = a;    //d中保存着和“a值一样的副本,它们互不影响”
a = 'I am different from d';
alert(d);    //输出'I am a string'
Copy after login

The above code is easy to understand, that is to say, the copy of variables accessed by value “What’s yours is yours, what’s mine is mine, we all have copies and do not affect each other.” And for variables accessed by value, Access by reference is slightly different:

var e = {
name : 'I am an object',
setName : function(name){
this.name = name;
}
};
var f = e;    //赋值操作,实际上的结果是e,f都是指向那个对象的引用指针
f.setName('I am different from e,I am object f.');
alert(e.name);    //对f进行操作,e的值也改变了!
Copy after login

For reference type assignment, to put it bluntly, the pointer of the object is copied. Both pointers point to the same entity object. There is no copy, and the original object remains only one! good. The above is the biggest and most fundamental difference between basic types and reference types! I use a picture to express it vividly:

How variables are stored in JavaScript

* Basic type variables and object pointers are stored in the stack memory; object entities are stored in the heap

How variables are stored in JavaScript

*Copy the front and rear stacks and heaps The situation in

Problems caused by reference types

1. The problem of using the prototype model to create objects

We all know that in JavaScript OO (Object Oriented), the biggest benefit of using the prototype model to create objects is that it can make object instances Share the properties and methods contained in the prototype. This avoids the shortcomings of the constructor pattern, that is, each object will have a copy of each method, and each method will be recreated on each instance, making method reuse meaningless.

Well, using the prototype pattern shares methods for all instances, but when there are properties with reference type values ​​in the prototype, the problem arises:

var Person = function(){
};
Person.prototype = {
constructor : Person,
name : 'Hanzongze',
hobby : ['basketable', 'swiming', 'running'],    //注意,这里包含着一个引用类型的属性
sayName : function(){
alert(this.name);
}
};
var person1 = new Person();
var person2 = new Person();
person1.hobby.push('music');
alert(person2.hobby);    //输出为'basketable', 'swiming', 'running','music'
alert(person1.hobby === person2.hobby);    //true
Copy after login

Since the hobby property is a reference type value, it is used by the Person constructor The hobby attributes of the created instances will all point to this reference entity, and the attributes between instance objects interfere with each other. This is not the result we want. To avoid this type of problem, the solution is to use a combination of constructor model and prototype model:

var Person = function(){
this.name = 'Hanzongze';
this.hobby = ['basketable', 'swiming', 'running'];    //对引用类型的值使用构造函数模式
};
Person.prototype = {
constructor : Person,
sayName : function(){
alert(this.name);
}
};
var person1 = new Person();
var person2 = new Person();
person1.hobby.push('music');
alert(person2.hobby);   //输出 'basketable', 'swiming', 'running',说明对person1的修改没有影响到person2
alert(person1.hobby === person2.hobby);    //false
Copy after login

2. Problems in prototypal inheritance

The essence of this problem is actually the same as the previous one. It just happens in the context of prototypal inheritance. Look at a prototype chain inheritance problem:

var Person = function(){
this.name = 'Hanzongze';
this.hobby = ['basketable', 'swiming', 'running'];
};
Person.prototype = {
constructor : Person,
sayName : function(){
alert(this.name);
}
};
//子类型Student
function Student(){
}
Student.prototype = new Person();    //Student继承了Person
var student1 = new Student();
var student2 = new Student();
student1.hobby.push('music');    //对子类实例student1的引用属性做了改动
var student3 = new Student();
alert(student2.hobby);    //输出'basketable', 'swiming', 'running', 'music'
alert(student3.hobby);    //输出'basketable', 'swiming', 'running', 'music'
Copy after login

In this code, you can see that the subclass Student inherits from the parent class Person. But since prototypal inheritance is used, that is to say, the instance of the parent class serves as the prototype of the subclass, so the reference type attributes in the instance are also inherited in the prototype prototype of the subclass. Instances of the subclass share the reference attribute and influence each other.

The solution is to use the borrowed constructor solution (but it is not an ideal solution. The ideal solution is to use a combination of prototype chain and borrowed constructor. It involves a lot of inheritance patterns. I will briefly describe it here. I will write an article in the future. Detailed article):

var Person = function(){
this.name = 'Hanzongze';
this.hobby = ['basketable', 'swiming', 'running'];
};
Person.prototype = {
constructor : Person,
sayName : function(){
alert(this.name);
}
};
function Student(){
//借用构造函数,继承了Person
Person.call(this);
}
var student1 = new Student();
var student2 = new Student();
student1.hobby.push('music');
alert(student2.hobby);    //输出'basketable', 'swiming', 'running', 'music'
Copy after login


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 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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

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

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

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:

jQuery usage practice: several ways to determine whether a variable is empty jQuery usage practice: several ways to determine whether a variable is empty Feb 27, 2024 pm 04:12 PM

jQuery is a JavaScript library widely used in web development. It provides many simple and convenient methods to operate web page elements and handle events. In actual development, we often encounter situations where we need to determine whether a variable is empty. This article will introduce several common methods of using jQuery to determine whether a variable is empty, and attach specific code examples. Method 1: Use the if statement to determine varstr="";if(str){co

See all articles