简体   繁体   中英

Is it possible to store a chunk of JS in a variable?

I realize this might go into the "worst practices" column but as an experiment I'm trying to refactor a function to the smallest length possible.

The following two lines work great.

 let prefix = document.querySelectorAll(".box")[0]; prefix.style.position = "absolute"; 

But when I tried to include code with the target it imploded.

 let prefix = 'document.querySelectorAll(".box")[0].style.position'; [prefix] = "absolute"; 

Is something like that even possible or have I crossed the line into a no-go zone? Thanks so much for any shove in the right direction!

You could return the code from a function handle as follow;

var prefix=function(position){
    document.querySelectorAll(".box")[0].style.position=position;
};

you can use it like this;

prefix("absolute");

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