例1:
function a(){ var user = "yao"; console.log(this.user);//undefined console.log(this);//window } a();等价于:
function a(){ var user = "yao"; console.log(this.user);//undefined console.log(this);//window } window.a();this指向的是window。
例2:
var o = { user:"yao", fn:function () { console.log(this.user);//yao } } o.fn();this指向的是o。
例3:
var o = { user:"yao", fn:function () { console.log(this.user);//yao } } window.o.fn();this指向的是o。
var o = { a:10, b:{ a:12, fn:function () { console.log(this.a);//12 } } } o.b.fn();this指向的是b。
例4:
var o = { a:10, b:{ a:12, fn:function () { console.log(this.a);//undefined console.log(this);//window } } }; var j = o.b.fn; j();综上所述:
this的指向永远是最终调用它的对象。
当this遇上函数的return:
例5:
function fn(){ this.user = "yao"; return {}; } var a = new fn; console.log(a.user);//undefined例6:
function fn(){ this.user = "yao"; return function(){}; } var a = new fn; console.log(a.user);//undefined例7:
function fn(){ this.user = "yao"; return 1; } var a = new fn; console.log(a.user);//yao例8:
function fn(){ this.user = "yao"; return undefined; } var a = new fn; console.log(a.user);//yao
this指向的是函数返回的那个对象。
function fn(){ this.user = "yao"; return null; } var a = new fn; console.log(a.user);//yao虽然:null是对象,但是此时this指向的仍然是函数的实例。
PS:
在"use strict"模式下,this默认的指向是undefined,而不是window。