this是函数体内自带的一个对象指针,它能够始终 指向 调用对象: 这个this代表的对象由this所在的执行作用域决定的,而不是根据this所在的定义作用域决定。
this[.属性],如果this未包含属性,则直接传递的是当前对象
1.this代表当前操作对象
<input type="button" value="你好" οnclick="this.value=' 哈哈,你好啊'"> //this即代表 对象 input
2.this代表构造函数的当前实例
function F(){ this.name="Owen"}
var f=new F(); //this即代表当前实例对象f
console.log(f.name);//Owen
3.this代表当前对象直接量
var o={
name:"我是对象o",
me:function(){return this;}//this代表对象直接量o
}
var who=o.me();
console.log(who.name);
4.this代表全部对象window
function f(){this.name="我是Owen";}//等价window.f=function(){this.name="我是Owen";}
f();//等价window.f();
console.log(name);//等价window.name
5.代表当前作用域对象
var f=function(){console.log(this)}
f();//this即代表window
new f();//this代表新创建的实例对象f
6、函数的调用与引用
1.以值的方式传递f()
function f(){return this;}
var o={
name:"对象o",
me:f,
o1:{
name:"对象o1",
me:f,
o2:{
name:"对象o2",
me:f,
}
}
}
var who=o.o1.o2.me();
console.log(who.name);//"对象o2"
var who=o.o1.me();
console.log(who.name);"对象o1"
var who=o.me();
console.log(who.name);"对象o"
2.不是以值的方式传递f(),而是直接调用
var name="我是window";
function f(){return this;}
var o={
name:"对象o",
me:f(),
o1:{
name:"对象o1",
me:f(),
o2:{
name:"对象o2",
me:f(),
}
}
}
var who=o.o1.o2.me;
console.log(who.name);//"我是window"
var who=o.o1.me;
console.log(who.name);//"我是window"
var who=o.me;
console.log(who.name);//"我是window"
3\函数的调用与引用2
var o={
name:"对象o",
f:function(){return this;}
}
o.o1={
name:"对象o1",
me:o.f //引用对象o的方法f
}
var who=o.o1.me();
console.log(who.name);//"对象o1"
o.o1={
name:"对象o1",
me:o.f () //调用对象o的方法f
}
var who=o.o1.me;
console.log(who.name);//"对象o"
7、call() 和apply()改变this的指向
function f(){
if(this.constructor==arguments.callee){
console.log("this=实例对象");
}else if(this==window){
console.log("this=window对象");
}else{
console.log("this==其他对象\n this.constructor="+this.constructor);
}
}
f();// this=window对象 this指向window
new f();//this=实例对象 this指向实例对象
f.call(1);/this==其他对象,这里是Number对象 /this指向数值实例对象
//call()将函数f()强制转换为对象o的一个方法
function f(){console.log(this.x+this.y);}
var o={x:1,y:2}
f.call(o);//3
8、异步调用之事件处理函数
异步调用就是通过事件机制或者计时器来延迟函数的调用时间和时机
<input type="button" value="Button"/>
<script>
var o={};
o.f=function(){
if(this==o){console.log("this=o");};
if(this==window){console.log("this=window")};
if(this==button){console.log("this=button");}
}
// button.οnclick=o.f;//this指向button。但在IE中this会指向window和button,符合dom标准的仅仅指向button
//兼容ie
if(window.attachEvent){
button.attachEvent("onclick",function(){
o.f.call(o);
})
}else{
button.addEventListener("click",function(){
o.f.call(o);
},true);
}
</script>
异步调用定时器:
var o={};
o.f=function(){
if(this==o){console.log("this=o");};
if(this==window){console.log("this=window")};
if(this==button){console.log("this=button");}
}
//setTimeout(o.f,100); //IE不兼容
setTimeout(function(){o.f.call(o)},100);