0

In javascript, if a function creates a function and then returns it, the returned function's scope is relative to where it was created.

I'm wondering if it's possible to have a block of code stored in a variable which acts almost like preprocessor macros in C/C++, but with the difference being it can be treated like a variable? Where, essentially, you create this macro, assign it to a variable, and wherever the macro is executed, the scope of the code is always relative to where it was executed.

An example (not real code):

macro someMacro {
    this.i++

    a++
}

function someFunc() {
    this.i = 0;

    var a = 0;

    console.log(this.i, a) // 0, 0

    someMacro();

    console.log(this.i, a) // 1, 1
}

I saw this question, but that's not quite what I want.

Thanks.

6
  • Maybe you're looking for .bind() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 8, 2015 at 9:21
  • 1
    For a there is imho no way except doing some dirty eval stuff. But I think the question is why you would like to do that. If someone reads your code no one would expect that someMacro() could/would change a, so this would be bad practice anyway. Commented Sep 8, 2015 at 9:27
  • @Lauromine, No, I know how to use .bind, I use it all of the time. I thought it was a bit of a longshot, this question. I've been using JavaScript for about 6 years now, I did think it was unlikely that I would have missed a feature such as the one I described in my question. Commented Sep 8, 2015 at 9:27
  • @t.niese, I believe you are correct. I think this could be a handy feature if ever standardised in the spec, but of course it's not a requirement to have this feature. I was just curious to know if I'd somehow overlooked such a capability of JavaScript over the years. Commented Sep 8, 2015 at 9:28
  • Perhaps you want sweetjs which provides macros as a transcompiler. Commented Sep 8, 2015 at 9:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.