Search code examples
javascriptoopinstance-variablesclass-variables

In most OOP Languages, does "i" in an instance method refer first to local, and then to global, but never to an instance variable or class variable?


In the following code:

    <script type="text/javascript">

        var i = 10;

        function Circle(radius) {
            this.r = radius;
            this.i = radius;
        }

        Circle.i = 123;

        Circle.prototype.area = function() { alert(i); }

        var c = new Circle(1);
        var a = c.area();

    </script>

What is being alerted? The answer is at the end of this question.

I found that the i in the alert call either refers to any local (if any), or the global variable. There is no way that it can be the instance variable or the class variable even when there is no local and no global defined. To refer to the instance variable i, we need this.i, and to the class variable i, we need Circle.i. Is this actually true for almost all Object oriented programming languages? Any exception? Are there cases that when there is no local and no global, it will look up the instance variable and then the class variable scope? (or in this case, are those called scope?)

the answer is: 10 is being alerted.


Solution

  • Behold:

    var i = 10;
    
    function Circle(radius) {
                var i = radius || 0;
                this.r = i;
                this.i = radius;
                this.toString = function(){ return i; };
            }    
    var nwCircle = new Circle(45);
    
    alert(nwCircle.r); //=>45;
    alert(nwCircle); //=>45 (toString found local i);
    alert(i); //=>10
    

    Now, in the Circle constructor you created a closure to the (local, belonging to the object itself) variable i. The globally defined i is unaffected. So, in javascript it depends on where you define your variable. In javascript at least, a bottom up search (from the local scope to the global scope) is done for i and the first one found is used. So if the Circle constructor didn't contain a variable called i, the global i would be used.