zoukankan      html  css  js  c++  java
  • 关于js作用域问题

    补充:

    function Foo(name,age){
        this.name=name;
        this.age=age;
        this.getName=function(){
            console.log(this);
        }
            
    }
    
    obj = new Foo("文州",19)
    obj.getName()    
    //这里把Foo看成类,大写是类,首字母小写是函数
    
    
    function test(){
        console.log(this);
    }
    
    test()=== window.test()
    //函数执行相当于window.test().所以打印的this是window对象。
    
    (function(){
        console.log(this)
    })()
    
    这个叫自执行函数。this指的还是window。
    
    
    
    
    题目0
    var name="女神"
    function Foo(name,age){
        this.name=name;
        this.age=age;
        this.getName=function(){
            console.log(this);
            
            (function(){
                console.log(this.name)   //自执行函数里面是window对象
            })()
        }
    }
    
    obj = new Foo("文州",19)
    obj.getName() 
    第一次打印文州,第二次打印女神
    
    
    
    想要都打印文州的话
    题目1
    var name="女神"
    function Foo(name,age){
        this.name=name;
        this.age=age;
        this.getName=function(){
            console.log(this);
            var that =this    //把当前环境的this赋值给that.那么这样2个都打印文州
            (function(){
                console.log(that.name)   
            })()
        }
    }
    
    obj = new Foo("文州",19)
    obj.getName() 
    
    //这样2个都执行文州。
    
    题目2
    var name="女神" obj={ name:'文州', age:19, getName:function(){ console.log(this); var that =this (function(){ console.log(that.name) })() } } obj.getName() //这个结果和上面的一样。只是(对象)的声明方式改变了而已。

  • 相关阅读:
    s3c6410时钟初始化
    一句话题解&&总结
    2019-9-2-本文说如何显示SVG
    2019-9-2-本文说如何显示SVG
    2018-8-3-WPF-读取硬件序列号
    2018-8-3-WPF-读取硬件序列号
    2018-8-10-win10-uwp-调试软件启动
    2018-8-10-win10-uwp-调试软件启动
    2018-8-10-使用-RetroShare-分享资源
    2018-8-10-使用-RetroShare-分享资源
  • 原文地址:https://www.cnblogs.com/geogre123/p/9792748.html
Copyright © 2011-2022 走看看