两道JS题

第一题
var v = 123;
function foo(){
       var v = 456;
       function inner(){
          console.log(v)
          }
          return inner
      }
result = foo();
result();
     

  

第二题
   var Name = 'root';
        var Age = 18;
        function Foo(name, age){
            this.Name = name;
            this.Age = age;
            this.Func = function(){
                console.log(this.Name, this.Age);
                (function(){
                    console.log(this.Name, this.Age);
                })();
            }
        }
        var obj = new Foo('alex', 16);
        obj.Func();

  第一题考的是JS的作用域,记住JS为函数为一个作用域,console.log(v)本身函数中没有v,所以要上上一级寻找,所以输出456

  第二题:

    1、JS的面向对象

function Func(name, age){
        this.Name = name;
        this.Age = age;
}
obj = new Func('root', 18)
# obj = new调用的时候, this相当于obj

    2、this是关键。

    每个函数中都有this。

    函数调用时 this = window

    类new时 this=调用对象

    function Func(){
        console.log(this);
}
    #当做函数执行函数时, this = window

   3、JS中无字典,只有对象

Name = 'alex'
obj = {
            Name:'root',
            Age:18,
            Func: function(){
                    #this = obj
                    console.log(this.Name) #向上一级寻找,第一个为'root’
                    var that = this #此时this为obj
                    function inner(){
                            console.log(that.Name) #that在本函数中没有向上一级寻找,所以是root
                            console.log(this.Name) # this为window,输出为alex
                     }
                     inner()
            }
}
obj.Func()
#自执行函数
(function(){
       console.log(this)

})()
this 为wendow    

  所以第二题答案为

alex 16
root 18

posted on 2018-02-26 19:21  xiao小  阅读(104)  评论(0编辑  收藏  举报

导航