两道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

转载于:https://www.cnblogs.com/xqxiaoxiao/p/8474710.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值