Javascript variable scope within onload function

This question already has an answer here:

  • What is the scope of variables in JavaScript? 25 answers

  • You're accessing b outside the function it was declared in.

    The local scope is function-oriented.

    so in:

    window.onload = function() {
        var b = "b";
        var p = new Person();
        p.doIknowAorB()'
    }
    

    b is a local variable for the anonymous (un-named) function which is connected to onload.

    but inside the function doIknowAorB in p :

    Person.prototype = function(){
        function doIknowAorB() {
            console.log(a);
            console.log(b);
        };
        return {
            "doIknowAorB": doIknowAorB
        }
    }();
    

    There is obviously no b . You can access a as it's a global variable.


    Because b becomes a local variable or a private variable of the anonymous function.

    Scope in javascript is function oriented.

    So, it cannot be accessed outside that function block.

    链接地址: http://www.djcxy.com/p/40834.html

    上一篇: 为什么参数在函数外保留其值?

    下一篇: onload函数中的Javascript变量范围