简体   繁体   中英

Custom block javascript?

I know this is a bit of a dumb question. Is it possible to make a custom block in javascript? This is a block:

if(a==2){
    "block!"
}

This is a block:

for(;;){
    "block!"
}

Is it possible? I've never seen anything about this subject. Is there a possibility of this being implemented in es6?

It would be great for callbacks, It would allow you to do this:

foo{
    ...
}

Instead of this:

foo(function(){
    ...
}

I think you'd like Ruby.

But no, there isn't a way to do this in JavaScript, and I haven't heard of any similar es6 features.

You can use labels to create blocks in JavaScript but they're only useful if you want to break from them as afaik you can't do anything else with them and they don't have their own scope (with the exception of let ).

foo: {
   // this is a block
   console.log(1);
   break foo;
   console.log(2); // never logged
}

As I know, JavaScript only have function scope, global scope and there is no block scope just like C. So currently you can't do this. If you want a block you have to wrap it in a function, you have already listed.

I've seen this trick that gives you a block with it's own scope for a variable using try/catch:

try {
  throw 0;
} catch(variable) {
  //variable only exists in this block
  variable = 'my value';
  console.log(variable);
  //i can return from parent function here
}
//variable does not exist outside of the block
console.log(typeof variable);

There are performance considerations with using try/catch but it's useful because it still allows use of return or break if the block is inside a function or loop.

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