片段1
var myObj = { fullname: "Hou Yi", getFullName: function(){ var self = this; console.log('outer:this.fullname is ' + this.fullname);//this.fullname is Hou Yi console.log('outer:self.fullname is ' + self.fullname);//self.fullname is Hou Yi (function(){ // 自执行函数的this一般情况下都指向window console.log('inner:this.fullname is ' + this.fullname);//this.fullname is undefined console.log('inner:self.fullname is ' + self.fullname);//self.fullname is Hou Yi })(); } }; myObj.getFullName();
片段2
//闭包 var fullname = "Camille Hou"; var myObj = { fullname:"Hou Yi", getFullName:function(){ return function(){ return this.fullname; } } } console.log(myObj.getFullName()());//Camille Hou
var fullname = "Camille Hou"; var myObj = { fullname:"Hou Yi", getFullName:function(){ var that = this; return function(){ return that.fullname; } } } console.log(myObj.getFullName()());//Hou Yi
片段3
var fullname = "Camille Hou"; var myObj = { fullname:"Hou Yi", getFullNameP:{ fullname:"Gamiye", getFullName:function(){ return this.fullname; } } }; //this指向myObj.getFullNameP /* 如果函数,被某一个对象所拥有,那么该函数在调用时,内部的this指向该对象。 */ console.log(myObj.getFullNameP.getFullName());//Gamiye var getName = myObj.getFullNameP.getFullName; // this指向window,getName被隐式的作为全局对象的属性。 /* 如果函数独立调用,那么该函数在调用时,内部的this指向undefined。但是在非严格模式中,当this指向undefined时,它会被自动指向全局对象。 */ console.log(getName());//Camille Hou
严格模式
'use strict' var fullname = "Camille Hou"; var myObj = { fullname:"Hou Yi", getFullNameP:{ fullname:"Gamiye", getFullName:function(){ return this.fullname; } } }; var getName = myObj.getFullNameP.getFullName; console.log(getName());//Cannot read property 'fullname' of undefined,此时的this指向undefined