Differences in reference types and value types in JavaScript

Source: Internet
Author: User

First, the storage method is not the same

Basic data types

Variables store simple data segments, store specific values , and are lightweight data storage methods

Reference type

The value of a reference type, an object that can consist of multiple values, a variable of a reference type stores an object reference address . The reference type is the weight of the data storage method , allocated in heap memory , and frequently created object lossy performance.

Reference type (n-Multi) Object, Array, Date, Function 、......

Second, dynamic properties are not the same

1. Reference types can add properties dynamically

var person=new Object ();

Person.name= "Jack";

person.age=20;

Console.log ("Name:%s, Age:%d", person.name,person.age);

Results

Description

Property dynamically added successfully

2. Value types cannot be added

Three, the way to assign value is different

1, value type, copy the contents of the variable

Value type, copying the contents of a variable

var num=10;

var num2=num; //Create new space, copy Num's value to num2.

The contents of this two variable are not affected, and the content of num2 is a copy of Num. Copy of similar operating system

var num=10;

var num2=num;

num2=100; //Does not affect the value of Num

Console.log ("num=%d num2=%d", num,num2);

Results

2. Reference type, copy reference address

var person1=new Object ();

person1.age=18;

var Person2=person1; //Copy the reference address, person2 the variable, and point to an object

person2.age=30; //is actually the object that Person1 pointed to.

Console.log ("person1.age=%d person2.age=%d", person1.age,person2.age);

Results

Description

Two variables all point to the same object, and the object is to be referenced by the variable, and there is no limit to the number of references.

Differences in reference types and value types in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.