Home > Web Front-end > JS Tutorial > How to pass an object in js

How to pass an object in js

(*-*)浩
Release: 2019-05-24 14:39:31
Original
3608 people have browsed it

Height mentioned: ‘The parameters of all functions in ECMAScript are passed by value’.

This is like copying a value from one variable to another.

How to pass an object in js

The value of the reference type is also the same as the basic type?

Example 1:

var person  = {
    name : "leaf"
};
function obj(o){
    o.name = "kafu";
   return o;
}
var result = obj(person);
console.log(result.name);// kafu
console.log(person.name);// kafu
Copy after login

Why does it look like the result is that the parameters of reference type are passed by reference?

Example 2:

var person = {
    name : "leaf"
};
function obj(o){
    o = {
       name : "kafu"
    };
    return o;
}
var result = obj(person);
console.log(result.name);// kafu
console.log(person.name);// leaf
Copy after login

Difference:

In example 1, person is passed to obj(). In fact, That is to copy the reference of the person object and pass it to o (can be regarded as an address). Person and o point to the same object at the same time. Modifying the attributes in o actually modifies the name attribute of the object they jointly point to. Because there is only one object in the memory area at this time.

Two examples. The o address points to another newly created object. At this time, there are two objects in the memory. Any changes to the new object pointed to by o will have no impact on the old object pointed to by person. of.

Why is it said that ‘the parameters of all functions in ECMAScript are passed by value’.

I won’t talk about the basic types.

For reference types, the passing of parameters is a reference copy of the passing object. It is equivalent to passing a new address after a copy. This copy address can actually be understood as passing by value (also called shared passing).

Use objects to pass as parameters

When passing objects as parameters, you don’t need to consider the order of the parameters, which is very useful.

The above is the detailed content of How to pass an object in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
js
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template