zoukankan      html  css  js  c++  java
  • js对象与this指向

    创建对象的方法

    1.对象字面量法

    var obj={}
    var obj={
    'first-name':'Tom',
    'last-name':'bush',
     age:24,
    Family:{
    Brother:’tony’,
    Father:’jack’
      }
    }

    对于合法的js标示符且不是表达式,并不强制要求用引号扩住属性名,对于不合法的标识符,则引号是必须的,'first-name',对象可以嵌套

     

    2.数组字面量法

    var box=['a','b',3,4,5];
    alert(box[1]); //b
    //遍历
    for(x in box){
    document.write(x+":"+box[x]+"<br/>");
    }
    //0:a
    //1:b
    //2:3
    //3:4
    //4:5
    //不可以box['x']或box.x

    二.this 指向

    在全局里this指向window,在某个对象里 this指向该对象,但在闭包里this却指向window

    看以下代码

     

    var user="the Window";
    var box={
        user:'the box',
        getThis:function(){
            return this.user;
        },
        getThis2:function(){
            return function (){
                return this.user;
            }
        }
    };
    
    alert(this.user);//the Window
    alert(box.getThis());//the box
    alert(box.getThis2()());//the Window
    alert(box.getThis2().call(box));//the box  对象冒充

     

    闭包不属于这个对象的属性或方法所以指向全局

    还有一种解决方法

    var box={
       user:'the box',
        getThis:function(){
            var that=this;//指向box
            return function(){
                return that.user;
            }
        }
    }
    alert(box.getThis()());//the box

     

     

     

  • 相关阅读:
    【AGC010E】Rearranging(博弈,图论,拓扑排序)
    【ARC074F】Lotus Leaves(最小割)
    【ARC069F】Flags(2-SAT,Tarjan,线段树优化建图)
    [CTS 2019] 氪金手游
    HDU
    LOJ
    LOJ
    [TJOI 2015] 概率论
    [AGC 018F] Two Trees
    LOJ
  • 原文地址:https://www.cnblogs.com/HKUI/p/3333461.html
Copyright © 2011-2022 走看看