情况一: 在方法中使用this
1 var fruits = { 2 one: "coconut", 3 two: "chestnut ", 4 eat: function () { 5 console.log(this.one + " " + this.two); 6 console.log(fruits.one + " " + fruits.two); 7 } 8 } 9 fruits.eat(); 10 // coconut chestnut 11 // coconut chestnut
在上面的代码中,我们定义了一个具有属性one,two,和eat的对象fruits,其中eat是一个函数,函数体内使用2种不同的方法输出make和model。
使用this时,this.one + " " + this.two 中的 this 指的是在上下文中的对象,也就是fruits,则this.one 为 fruits.one, this.two 为 fruits.two
使用点操作符时,我们可以直接访问对象的属性 fruits.one 和 fruits.two
情况二: 在方法中使用this
函数中的this就有些复杂了。与对象一样,函数也具有属性,函数每次执行时都会获取this,它指向调用它的对象。
如果函数未被某对象调用,则函数内的this属于全局对象,该全局对象被称为 window。在这种情况下,this 将指向全局作用域中的变量。如下例所示:
1 var one = "coconut"; 2 var two = "chestnut" 3 function eat() { 4 console.log(this.one + " " + this.two); 5 } 6 var fruits = { 7 one: "coconut", 8 two: "chestnut", 9 eat: function () { 10 console.log(this.one + " " + this.two); 11 } 12 } 13 fruits.eat(); // coconut chestnut 14 window.eat(); // coconut chestnut 15 eat(); // coconut chestnut
在该例中,在全局对象中定义了one,two,和eat,对象fruits中也实现了eat 方法。当使用fruits调用该方法时,this指向该对象内的变量,而使用另外两种调试方式时,this指向全局变量
情况三: 单独使用this
1 var one = "coconut"; 2 var two = "chestnut" 3 4 console.log(this.one) //coconut 5 console.log(this.two) //chestnut
当单独使用this,不依附与任何函数或者对象时,指向全局对象,这里的this指向全局变量name
情况四: 在事件内使用this
JS中有很多事件类型,但为了描述简单,这里我们以点击事件为例。
每当单机按钮并触发一个事件时,可以调用另一个函数来去执行某个任务。如果在函数内使用this,则指向触发事件中的元素。DOM中,所有的元素都以对象的形式储存,也就是说网页元素实际就是DOM中的一个对象,因此每触发一个事件时,this就会指向该元素。
五: call(), apply() & bind() 的使用
bind: 允许我们在方法中设置this指向
call&apply: 允许我们借助其他函数并在函数调用中改变this的指向