简体   繁体   中英

How can i put constants in a function and not make them global

How can i put constants in a function (fullpage, i guess) and not make them global. I think this is a bad practice. But I do not want to duplicate them in each event, I would like to indicate only once. I would like to know what can be done with this.

 // This constants const tl = new TimelineMax({ delay: 0.5 }); const title = destination.item.querySelector("h1"); new fullpage('#fullpage', { navigation: true, afterLoad: function (destination) { // I do not want to repeat them here if (destination.index === 0) { tl.fromTo(title, 1, { y: "20", opacity: 0 }, { y: "0", opacity: 1 }); } }, onLeave: (destination) => { // And here tl.fromTo(title, 1, { y: "20", opacity: 0 }, { y: "0", opacity: 1 }); if (destination.index === 1) { const chairs = document.querySelectorAll(".chair"); const description = document.querySelector(".description"); // Here i animate "chairs" and "description" } } })

Wrap the code in an IIFE so they are scoped to that function.

(function () {
    const foo = 1; // Local to the function defined on the previous line

    // and accessible to any function defined here
})();

Note that the title is not really a constant, so what you need is simply a function.

{
const tl = new TimelineMax({delay: 0.5});
const title_of = x => x.item.querySelector("h1");

new fullpage('#fullpage', {

  //well why you use normal function here (I shortened it a little)
  afterLoad(destination) {
    const title = title_of(destination)
    //...
  },

  //and arrow function here?
  onLeave: (destination) => {
    const title = title_of(destination)
    //...
  }
})

** This block of answer doesn't really reflect OP's need, but since it answer the title, I'd keep it here. **

simply wrap them in a block. since const define a block level variable

{
   const tl = new TimelineMax({ delay: 0.5 });
   const title = destination.item.querySelector("h1");

   new fullpage('#fullpage', {...})
}

You can simply put your code within a block as const and let are block-scoped [1]:

{
  const tl = new TimelineMax({ delay: 0.5 });
  const title = destination.item.querySelector("h1");

  new fullpage('#fullpage', {
    // you can use `tl` and `title` here`...
  })
}

// ...but not here
console.log(tl) //=> ReferenceError: tl is not defined

[1] https://wesbos.com/javascript-scoping/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM