Home  >  Q&A  >  body text

Object key exists outside function call but not within function scope

I'm using fabric.js and at one point I used the following code:

canvas.on("object:modified", (opt) => {
  console.log(opt.action); //="scale"
  handleScaled(opt);
});

But in the handleScaled function opt.action is undefined:

function handleScaled(opt) {
  console.log(opt.action) //=undefined
  console.log(opt) //displays the whole opt object but there is no "action" in it
  //further handleScaled code
}

console.log(opt.action) before the function call displays "scale" correctly, but when I call the same in handleScaled, opt .log(opt.action) will display "scale" correctly. Operation is undefined.

Why does opt.action not seem to exist within the scope of the called function, but exists just before the call?

Correct working code only calls handleScale when the operation is "scale":

canvas.on("object:modified", (opt) => {
  if (opt.action === "scale") {
    handleScaled(opt);
  }
});

P粉133321839P粉133321839373 days ago455

reply all(1)I'll reply

  • P粉356361722

    P粉3563617222023-09-13 00:36:00

    In your code, when you log opt.action before calling the handleScaled function, it will correctly display "scale" because it is accessing the action The code> attribute of the opt object passed to the callback function of the canvas.on event handler. When you log opt.action in the handleScaled function, it appears as undefined because the opt object is passed to The handleScaled function is another instance of this object. It does not have an action attribute because it is different from the opt object recorded previously.

    To make opt.action accessible in the handleScaled function, you can modify the code like this:

    canvas.on("object:modified", (opt) => {
      console.log(opt.action); //="scale"
      handleScaled(opt);
    });
    
    function handleScaled(opt) {
      console.log(opt.action); // "scale" (should display correctly)
      // further handleScaled code
    }
    

    By passing the opt object directly to the handleScaled function, you retain access to its properties within the function scope. Ensure that the opt object passed to handleScaled contains the expected action properties.

    reply
    0
  • Cancelreply