admin管理员组

文章数量:1290099

I create a simple function node to demonstrate my problem:

var items=context.get('items');

if (items==undefined) {           // first run
    node.warn('Create items')
    var items={'item1':100}
    context.set('items',items)
    return
}
items.item1+=1;
node.warn(items)

On each iteration, the variable is read from the context storage and incremented. It is NOT saved using context.set(...). Nevertheless, the variable keeps increasing. The type of context used does not matter.

I could not observe this behavior with simple variables, i.e., non-JSON types. Is this a bug or a feature?

What is the explanation for this behavior?

I create a simple function node to demonstrate my problem:

var items=context.get('items');

if (items==undefined) {           // first run
    node.warn('Create items')
    var items={'item1':100}
    context.set('items',items)
    return
}
items.item1+=1;
node.warn(items)

On each iteration, the variable is read from the context storage and incremented. It is NOT saved using context.set(...). Nevertheless, the variable keeps increasing. The type of context used does not matter.

I could not observe this behavior with simple variables, i.e., non-JSON types. Is this a bug or a feature?

What is the explanation for this behavior?

Share Improve this question asked Feb 20 at 10:27 Gottfried PrandstetterGottfried Prandstetter 112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

NodeJS is a pass by reference language, so when you do the context.get() it does not return a copy of the object, it returns a reference to that object.

So the increment is not working on a local copy, it is working on the same object stored in the context.

It doesn't happen with a raw number, because that is not an object, but a primitive type.

This is working as intended.

This SO question covers what Pass by Reference means in more detail

What's the difference between passing by reference vs. passing by value?

本文标签: nodejsUnexpected behaviour of context itemsStack Overflow