Search code examples
javascriptfunctionconstructor

using passed argument in javascript function constructor


Here I'm trying to use a function constructor and then use that constructor to create a circle object.

const Circle1 = Function('radius,centerX,centerY',`
this.radius = radius;
this.centerX = centerX;
this.centerY = centerY;
this.draw = function(){
  console.log('drawing circle with radius ${this.radius}');
};
`);


const mycircle = new Circle1(5,10);
mycircle.draw();

When I run the code the result I see on the console is like this:

drawing circle with radius undefined

Is there a way that I can use those arguments passed to the function?

I tried to reach the value as ${radius} or ${this.radius} but both of them give the result as undefined. I was expecting to see the actual radius value.


Solution

  • Although all the comments about not needing to do this are right, the actual problem is that you are using a template literal for the function body, but you want to create another literal for the console log. So you need to use the back tick there as well, but you also need to escape the $ or it will apply to the outer literal and so the this.radius will mean nothing (in that context).

    const Circle1 = Function('radius,centerX,centerY', `
        this.radius = radius;
        this.centerX = centerX;
        this.centerY = centerY;
        this.draw = function(){
          console.log(\`drawing circle with radius \${this.radius}\`);
        };
        `);
        
    const mycircle = new Circle1(5, 10);
    mycircle.draw();