一:this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
实例一:函数this指向
function a(){ var user = "sly"; console.log(this.user); console.log(this); } a();//undefined //Window
window.a();//undefined //Window
解释:这里的a函数指向的是window;window.a();和a()指向的都是window
实例二:对象this指向
var o = { a:10, b:{ a:12, fn:function(){ console.log(this.a); } } } o.b.fn();//12 此时的this指向的是b对象var test = o.b.fn;
test();//this指向的是window,this.a 为undefined
解释:
var test = o.b.fn;这样赋值相对于
var test =function(){alert(this.a)}
test这个函数是在window中的,window里面并没有定义全局的变量a,所以this.a = undefined
实例三:构造函数this
function Fn(){ this.user = "12"; } var a = new Fn(); console.log(a.user); //12
解释:对象a.user获得值为12,因为new关键字改变了this的指向,将这个this指向对象a,
除了new关键字之外。call apply bind方法都可以改变this的指向。
2.如果函数中this,并且函数被上一级对象调用,this指向的就是上一级的对象。
3.