var name = 'this is window'; //定义window的name属性 function getName(){ console.log(this); //控制台输出: Window //this指向的是全局对象--window对象 console.log(this.name); //控制台输出: this is window / }
var name = 'this is window'; //定义window的name属性,看this.name是否会调用到 var testObj = { name:'this is testObj', getName:function(){ console.log(this); //控制台输出:testObj //this指向的是testObj对象 console.log(this.name); //控制台输出: this is testObj } }
var name = "this is window"; //定义window的name属性,看this.name是否会调用到 var testObj = { name : "this is testObj", getName:function(){ //var self = this; //临时保存this对象 var handle = function(){ console.log(this); //控制台输出: Window //this指向的是全局对象--window对象 console.log(this.name); //控制台输出: this is window //console.log(self); //这样可以获取到的this即指向testObj对象 } handle(); } }
var name = 'this is window'; //定义window的name属性,看this.name是否会调用到 var testObj1 = { name : 'this is testObj1', getName:function(){ console.log(this); //控制台输出: testObj2 //this指向的是testObj2对象 console.log(this.name); //控制台输出: this is testObj2 } }