J
J
jazzz132012-05-15 07:48:21
JavaScript
jazzz13, 2012-05-15 07:48:21

How to make scope in javascript?

Hey!

I'm not sure many people know the answer to this question.

The function defines its own scope - this is a certain object , the properties of which are the variables defined in the function.

Question: is it possible to refer to this object ?
Otherwise, is there access to full scope control?

Thank you!

PS inspired by this habrahabr.ru/qa/19385/

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
spmbt, 2012-05-15
@jazzz13

You can only access the global object, through window, self or this (the latter is for a function - not an object method). Even for internal functions with their own scope, this will be window.

<script>

(function(){
  var aa = function(){
    console.log(window==this, this)
  }
  aa()
})()

</script>
Local scope is not available. It was done, apparently, for the possibility of writing independent scripts on one page or, in other words, for another script not to influence the first one through the scope in any way (for example, to erase variables from it).

A
Anatoly, 2012-05-15
@taliban

There is no way you can access the list of external visible variables just by knowing their name, or if the function is at the top level, then you can override window.

S
Sergey, 2012-05-15
Protko @Fesor

Maybe I didn't quite understand the question, but...

var data = (function(){
    var a = "provate string";
    var b = "public string;";

    return {
        a: a
    };
})();

in the following way, imitation of private properties is usually achieved. Usually used for private methods/properties and exports an object containing getters and setters.
If you need to have access to all internal variables, then it makes sense to publish them via this.prototype. Then all you have to do is instantiate your function and access the published properties. Perhaps you can limit yourself to only this, but here I will not tell you for sure. Need to try.

S
Skpd, 2012-05-15
@Skpd

Maybe I'm misunderstanding something, but the scope of a function is either the window object , or any other object passed using .call() or .apply().
Therefore, we always know what kind of object it is and have access to full visibility control.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question