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

How to pass an object in js

(*-*)浩
(*-*)浩Original
2019-05-18 17:39:533517browse

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

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

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!

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
Previous article:How to clear tr in jsNext article:How to clear tr in js