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

 

 

 

 

posted @ 2013-09-22 16:58  H&K  阅读(701)  评论(0编辑  收藏  举报