EzDevInfo.com

scope interview questions

Top scope frequently asked interview questions

What is the difference between my and our in Perl?

I know what my is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does our do? How does our differ from my?


Source: (StackOverflow)

Variable declared in for-loop is local variable?

I have been using C# for quite a long time but never realised the following:

 public static void Main()
 {
     for (int i = 0; i < 5; i++)
     {

     }

     int i = 4;  //cannot declare as 'i' is declared in child scope                
     int A = i;  //cannot assign as 'i' does not exist in this context
 }

So why can I not use the value of 'i' outside of the for block if it does not allow me to declare a variable with this name?

I thought that the iterator variable used by a for-loop is valid only in its scope.


Source: (StackOverflow)

Advertisements

var self = this?

Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this

function MyObject() {
  this.doSomething = function() {
    ...
  }

  var self = this
  $('#foobar').bind('click', function(){
    self.doSomethng()
    // this.doSomething() would not work here
  })
}

It works, but is that the best way to do it? It looks strange to me.


Source: (StackOverflow)

How do I pass the this context to a function?

I thought this would be something I could easily google, but maybe I'm not asking the right question...

How do I set whatever "this" refers to in a given javascript function?

for example, like with most of jQuery's functions such as:

$(selector).each(function() {
   //$(this) gives me access to whatever selector we're on
});

How do I write/call my own standalone functions that have an appropriate "this" reference when called? I use jQuery, so if there's a jQuery-specific way of doing it, that'd be ideal.


Source: (StackOverflow)

Using global variables in a function other than the one that created them

If I create a global variable in one function, how can I use that variable in another function?
Do I need to store the global variable in a local variable of the function which needs its access?


Source: (StackOverflow)

What is the scope of variables in JavaScript?

What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?


Source: (StackOverflow)

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.

(function() {
    ... 
    code
    ...
})();

What is the reason for doing this rather than a simple set of constructor functions?


Source: (StackOverflow)

JavaScript closures vs. anonymous functions

A friend of mine and me are currently discussing what is a closure in JS and what isn't. We just want to make sure we really understand it correctly.

Let's take this example. We have a counting loop and want to print the counter variable on the console delayed. Therefore we use setTimeout and closures to capture the value of the counter variable to make sure that it will not print N times the value N.

The wrong solution without closures or anything near to closures would be:

for(var i = 0; i < 10; i++) {
    setTimeout(function() {
        console.log(i);
    }, 1000);
}

which will of course print 10 times the value of i after the loop, namely 10.

So his attempt was:

for(var i = 0; i < 10; i++) {
    (function(){
        var i2 = i;
        setTimeout(function(){
            console.log(i2);
        }, 1000)
    })();
}

printing 0 to 9 as expected.

I told him that he isn't using a closure to capture i, but he insists that he does. I proved that he doesn't use closures by putting the for loop body within another setTimeout (passing his anonymous function to setTimeout), printing 10 times 10 again. The same applies if I store his function in a var and execute it after the loop, also printing 10 times 10. So my argument is that he doesn't really capture the value of i, making his version not a closure.

My attempt was:

for(var i = 0; i < 10; i++) {
    setTimeout((function(i2){
        return function() {
            console.log(i2);
        }
    })(i), 1000);
}

So I capture i (named i2 within the closure), but now I return another function and pass this around. In my case, the function passed to setTimeout really captures i.

Now who is using closures and who isn't?

Note that both solutions print 0 to 9 on the console delayed, so they solve the original problem, but we want to understand which of those two solutions uses closures to accomplish this.


Source: (StackOverflow)

What's the correct way to communicate between controllers in AngularJS?

What's the correct way to communicate between controllers?

I'm currently using a horrible fudge involving window:

function StockSubgroupCtrl($scope, $http) {
    $scope.subgroups = [];
    $scope.handleSubgroupsLoaded = function(data, status) {
        $scope.subgroups = data;
    }
    $scope.fetch = function(prod_grp) {
        $http.get('/api/stock/groups/' + prod_grp + '/subgroups/').success($scope.handleSubgroupsLoaded);
    }
    window.fetchStockSubgroups = $scope.fetch;
}

function StockGroupCtrl($scope, $http) {
    ...
    $scope.select = function(prod_grp) {
        $scope.selectedGroup = prod_grp;
        window.fetchStockSubgroups(prod_grp);
    }
}

Source: (StackOverflow)

What underlies this JavaScript idiom: var self = this?

I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo:

function Note() {
  var self = this;

  var note = document.createElement('div');
  note.className = 'note';
  note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
  note.addEventListener('click', function() { return self.onNoteClick() }, false);
  this.note = note;
  // ...
}

The author uses self in some places (the function body) and this in other places (the bodies of functions defined in the argument list of methods). What's going on? Now that I've noticed it once, will I start seeing it everywhere?


Source: (StackOverflow)

Short Description of Python Scoping Rules

What exactly are the Python scoping rules?

If I have some code:

code1
class Foo:
   code2
   def spam.....
      code3
      for code4..:
       code5
       x()

Where is x found? Some possible choices include the list above:

  1. In the enclosing source file
  2. In the class namespace
  3. In the function definition
  4. In the for loop index variable
  5. Inside the for loop

Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?

There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.


Source: (StackOverflow)

Access a variable outside the scope of a Handlebars.js each loop

I have a handlebars.js template, just like this:

{{externalValue}}

<select name="test">
    {{#each myCollection}}
       <option value="{{id}}">{{title}} {{externalValue}}</option>
    {{/each}}
</select>

And this is the generated output:

myExternalValue

<select name="test">
       <option value="1">First element </option>
       <option value="2">Second element </option>
       <option value="3">Third element </option>
</select>

As expected, I can access the id and title fields of every element of myCollection to generate my select. And outside the select, my externalValue variable is correctly printed ("myExternalValue").

Unfortunately, in options' texts, externalValue value is never printed out.

My question is: how can I access a variable outside the scope of the handlebars.js each from within the loop?

As always, thanks in advance.


Source: (StackOverflow)

How to choose the right bean scope?

I noticed that there are different bean scopes like:

@RequestScoped
@ViewScoped
@FlowScoped
@SessionScoped
@ApplicationScoped

What is the purpose of each? How do I choose a proper scope for my bean?


Source: (StackOverflow)

javascript: recursive anonymous function?

Lets say I have a basic recursive function:

function recur(data) {
    data = data+1;
    var nothing = function() {
        recur(data);
    }
    nothing();
}

How could I do this if I have an anonymous function such as...

(function(data){
    data = data+1;
    var nothing = function() {
        //Something here that calls the function?
    }
    nothing();
})();

I'd like a way to call the function that called this function... I've seen scripts somewhere (I can't remember where) that can tell you the name of a function called, but I can't recall any of that information right now.


Source: (StackOverflow)

Is it possible to declare two variables of different types in a for loop?

Is it possible to declare two variables of different types in the initialization body of a for loop in C++?

For example:

for(int i=0,j=0 ...

defines two integers. Can I define an int and a char in the initialization body? How would this be done?


Source: (StackOverflow)