How to decompose a return?

3

Suppose that the following return came from a function:

return {    
    x: 199,
    y: 200    
}

Eye: I can not change the return itself.

How can I then from where I receive the return modify it? That is, for example:

I got x:199 e y:200 and I want to add 20 How can I do it?

    
asked by Eduardo Sebastian 24.07.2017 в 04:20
source

4 answers

6

What you are returning is a Object , so you can access to the properties x e y of the object and alter them the way you want.

function someFunction(){
  return {
          x: 199,
          y: 200
         };
}

var obj = someFunction();
obj.x += 20;
obj.y += 20;
console.log(obj.x +","+obj.y);
    
answered by 24.07.2017 / 04:31
source
3

In your question you refer to

  

How to decompose a return?

Although later in the text you ask something slightly different, for completeness it is appropriate to talk about destructuring An option introduced in ES6 to "unpack" objects easily. In the example that you put if what you were interested in was really "decomposing" the object returned by the return you could do something like this:

function foo() {
    return {
        x: 199,
        y: 200,
    }
}

let {x, y} = foo();
x += 20; 
y += 20;
console.log(x); // 219
console.log(y); // 220
    
answered by 24.07.2017 в 08:48
0

It is best to create a function that adds functionality.

Imagine a function as follows

function Original(x,y)
{
  return {x,y}
}

You want to add a quick mechanism to add to both values, a certain number, therefore you create another function that abstracts the process, first copies the output of the Original function and defines a more comfortable prototype

   function EnvolturaSumar(i)
    {
      this.x += i
      this.y += i
    }

See the complete example:

function Original(x,y)
{
  return {x,y}
}

function Envoltura(x,y)
{
  if (this == window)
    throw new Error('debe utilizarse el operador new')
  Object.assign(this, Original(x,y)) 
}

function EnvolturaSumar(i)
{
  this.x += i
  this.y += i
}

Envoltura.prototype = Object.create(Object.prototype, {
   sumar: {value: EnvolturaSumar}
})

var x = new Envoltura(2,3)
console.log(x)
x.sumar(20)
console.log(x)
x.sumar(-10)
console.log(x)
    
answered by 24.07.2017 в 05:24
-2

function changeValorJson(){
  var a={};
  
          a.x= 1;
          a.y= 2;
         
         return a;
         
}
var valorJson = changeValorJson();
console.log(valorJson.x );
valorJson.x =valorJson.x + 100;

console.log(valorJson.x );

To access an attribute of a json object you must use . , example

valorJson.x
    
answered by 24.07.2017 в 06:21