this
this is the object that the function is a property of
- 单独的this
In this case,the window object is our global object.
this指的就是 global object,即this = window
console.log(this)
//this means window
function a(){
console.log(this)
}
a()
/*
this === window
this is the object that the function is a property of
That means we're calling window.a(),so,the function A is a property of the window object.
*/
- 在严格模式中单独的this
"use strict"
console.log(this)
// this means global object,so this = window
function a(){
"use strict"
console.log(this)
}
// this is undefined
- 对象方法中的this
(1).gives methods access to their object(properties or methods)
const obj = {
name: 'Billy',
sing(){
return 'lalala' + this.name
},
singAgain(){
return this.sing() + '!'
}
}
obj.sing()
// this means obj's object
(2).execute same code for multiple objects
function importantPerson(){
console.log(this.name)
}
const name = "Sunny";
const obj1 = {
name: 'Cassy',
importantPerson: importantPerson
}
const obj2 = {
name: 'Jacob',
importantPerson: importantPerson
}
importantPerson()
// Sunny,Sunny is a global variable, this means window,so this.name = Sunny
obj1.importantPerson()
// Cassy, this means obj1's object,so this.name = Cassy
obj2.importantPerson()
// Jacob
Exercise1
const a = function (){
console.log('a', this)
const b = function () {
console.log('b', this)
const c = {
hi: function(){
console.log('c', this)
}
}
c.hi()
}
b()
}
a()
/* a.this = window because window.a()
b.this = window because window.a(b())
c.this = c's object because c called hi()
*/
Exercise2
const obj = {
name: 'Billy',
sing(){
console.log('a',this);
var anotherFunc = function(){
console.log('b',this)
}
anotherFunc()
}
}
obj.sing()
/*
a.this is obj's object
b.this is window
注:It matters how the function was called
*/
解决嵌套函数this指向问题 (1).Arrow functions
const obj = {
name: 'Billy',
sing(){
console.log('a',this);
var anotherFunc = () => {
console.log('b',this)
}
anotherFunc()
}
}
obj.sing()
/* a.this is obj's object
b.this is also obj's object */
(2).bind(this)
const obj = {
name: 'Billy',
sing(){
console.log('a',this);
var anotherFunc = function() {
console.log('b',this)
}
return anotherFunc.bind(this)
}
}
obj.sing()()
/* a.this is obj's object
b.this is also obj's object */
(3).outsie of the function self,create a reference
const obj = {
name: 'Billy',
sing(){
console.log('a',this);
var self = this;
var anotherFunc = () => {
console.log('b',self)
}
anotherFunc()
}
}
obj.sing()
/* a.this is obj's object
b.this is also obj's object */