skip to Main Content

Is it possible to extract an Object out of a Function with JavaScript?

The function I received inside of an Object:

function item(){ let product = { name: name, price: price } }

I want to extract the Object: product out of that function. Caveat: The function may not be changed.

Extracting the Object product

2

Answers


  1. I guess the only way is to eval the function’s body:

    const name = 'name', price = 3;
    
    function item(){ let product = { name: name, price: price } }
    
    {
      const src = item.toString().match(/(?<=[^{]+{).+(?=})/)[0];
      console.log(eval(src + ';product'));
    }
    Login or Signup to reply.
  2. I am not sure about Caveat: The function may not be changed. If you mean the implementation of the function has zero tolerance to change anything, I believe there is not much of things we can do here. The logic is this:

    • Since your product is declared locally in that scope, the function itself must manage some way to give the reference of that product out. It must require some changes to that function implementation.
    • You are faced with a fundamental limitation of JavaScript’s scoping rules: variables declared within a function are local to that function and cannot be accessed from outside unless they are explicitly exposed.
      • This is not only limited by JavaScript but also many other languages share the same scope definition.

    If you do can have some tolerance on the changes of the function implementation, you can try the following changes:

    Method 1: Return the product inside a function

    {
        function item() { 
            let product = { name: name, price: price }; 
            return product;
        }
        const insideProduct = item();
    }
    

    Method 2: Use Closure

    {
        let product;
        function item() { 
            product = { name: name, price: price }; 
            return;
        }
        console.log(product);
    }
    

    Method 3: Use Global Variable

    {
        let product;
        function sendObjectOutside(obj) {
            product = obj;
        }
        
        function item() { 
            let product = { name: name, price: price }; 
            sendObjectOutside(product);
        }
    
        console.log(product);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search