2

I'm running into a funny issue in my (Javascript) code that I think has to do with scope. If this is the case, I'd like to understand scope in JS better.

I doubt this will be relevant, but I'm also working with React and D3.

The gist of my code is as follows:

// 1

export default class C extends Component {
    // 2

    componentDidUpdate() {
        // 3

        ...
        var node = svg.append('svg')
            .append('svg:image')
            .attr('xlink:href', function(d) {
                // 4

                return dict['foo'];
            });
    }
}

I'm trying to use the contents of an outside object within an anonymous function.

    dict = {
        foo: 'bar.svg'
    };

So far I've found that if I declare the above object in locations 3 or 4, the code executes just fine. However, if I move the object declaration outside the method (2), or outside the class entirely (1), I get an error: dict is not defined.

What about locations 1 and 2 makes them unavailable for use within the anonymous function?

mrshl
  • 531
  • 3
  • 12
  • `return this.dict['foo'];` – JohanP Jul 24 '18 at 01:28
  • 2
    AFAIK you can't declare class variables within a class declaration as yet. [This answer](https://stackoverflow.com/a/22986568/5217142) mentions using babel (which you would for react) may support this but I don't know how it is transpiled. The ECMAScript proposal to add class variables may be [this one](https://github.com/tc39/proposal-class-fields). – traktor Jul 24 '18 at 03:06

2 Answers2

1

I believe you should be able to use an arrow function.

export default class C extends Component {
    componentDidUpdate() {
        ...
        var node = svg.append('svg')
            .append('svg:image')
            .attr('xlink:href', (d) => this.dict['foo']);
    }
}
RustyDev
  • 1,094
  • 1
  • 9
  • 18
  • Interestingly enough, in an arrow function I'm able to use `this.dict['foo']`, but not in a traditional function. The follow discussion of arrow functions vs. regular functions helped me: https://stackoverflow.com/a/34361380/7531146 – mrshl Jul 24 '18 at 17:35
  • That's correct. Here's another example of how to use the arrow functions with class variables: https://codepen.io/rustydev/project/editor/DVMNze – RustyDev Jul 24 '18 at 19:51
-2

There are two scopes in javascript. Local scope and global scope. If you have function like

TestFunc() {
// here variable 'a' local variable in this function
// and you can't access 'a' outside of this function
 var a = 'test';
}

but if you have a class like
class TestClass {
 // here 'b' is a global variable of this class
 // and it can be accessed from any of the method of this class using 'this' keyword
 b: string;

 // example of method
 TestGFunction() {
 // here 'b' is a global variable of class 'TestClass'
  this.b = 'test3';
}
}

Hope it may help you to understand the concept of local and global scope in javascript.

Shahriat Hossain
  • 340
  • 4
  • 12