一,全局的this(浏览器)可以看做是window,
console.log(this===window)
//true
二,一般函数的this也是window(node.js是global object)
function f1(){
return this;
}
console.log(f1()===window);//true
严格模式下,this指向undefined
function f1(){
"use strict";
return this;
}
console.log(f1()===undefined);
//true
三,作为一般对象方法的函数的this指向该对象
var o={
prop:37,
f:function(){
return this.prop;
}
};
console.log(o.f());//37
临时添加的对象方法也可以,只要是通过o.f()调用,this就是指向o这个对象。
四,对象的原型链上的方法this,指向的是该对象。
var o={
f:function(){return this.a+this.b;}
}
var p=Object.create(o);
p.a=1;
p.b=4;
console.log(p.f());//5 this指向的是调用f()的p对象
五,get,set方法与this(暂时放着)
六,构造器中的this,指向的是原型是构造器函数的prototype属性的空对象
function MyClass(){
this.a=37;//没有返回值时返回的是this,指向MyClass.prototype属性的空对象
}
var o=new MyClass();
console.log(o.a);//37 //因此o也有a这个属性
七,call和apply方法与this
this指向的是作为第一个参数的对象
function add(c,d){
return this.a+this.b+c+d;
}
var o={a:1,b:3};
console.log(add.call(o,5,7));//16 也可以使用add.apply(o,[5,7]); //注意使用call时add函数已经执行,所以是返回值,可以直接输出。
(暂时放着)
八,bind方法与this
this指向绑定的对象(bind在绑定一次,重复调用时比apply和call更高效一点)
function f(){
return this.a;
}
var g=f.bind({a:'test'});//this指向传进来的对象,只是绑定,没有执行函数
console.log(g());//这里执行函数f()
var o={a:37,f:f,g:g};
console.log(o.f(),o.g());//37 "test"
//通过bind方法绑定后,即使新绑定后的方法作为对象的方法去调用,this仍然指向绑定的对象
</script>