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.

Community
  • 1
  • 1
thephpdev
  • 1,097
  • 10
  • 25
  • Maybe you're looking for `.bind()` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Lauromine Sep 08 '15 at 09: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. – t.niese Sep 08 '15 at 09: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. – thephpdev Sep 08 '15 at 09: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. – thephpdev Sep 08 '15 at 09:28
  • Perhaps you want [`sweetjs`](http://sweetjs.org/) which provides macros as a transcompiler. – Dan D. Sep 08 '15 at 09:32
  • I had come across sweetjs during my initial research before asking the question, but I'd prefer not to use a library. – thephpdev Sep 08 '15 at 09:35

0 Answers0