This指向

90 阅读1分钟

全局this

// html中   全局this => window
// nodejs中   全局this => module.exports

函数及对象

function move() {
    console.log(this)   // 非严格模式下:this;严格模式下:undefined
}
move() // 严格模式: window.move()
  • this指向调用它的对象
  • 函数被多层对象包含,函数被最外层对象调用时,this指向它的上一级对象
var obj = {
	a: 10,
	b: {
		fn: function() {
			console.log(this)
		}
	}
}
window.obj.b.fn() // b
  • 构造函数
erDiagram
constructedFunction ||--|{ return : return
constructedFunction ||..|{ noReturn : return
return ||--|{ returnedObject : object
return ||--|{ object : null
return ||--|{ object : notObject
noReturn ||--|{ object : notObject
// 无返回值时
function fn() {
    this.num = 10
    console.log(this)
}
fn.num = 20
fn.prototype.num = 30
fn.prototype.method = function (){ console.log(this.num)}
var proto = fn.prototype
var method = proto.method
new fn().method()    // 10
proto.method()       // 30
method()             // undefined

// 有返回值时
function fn1() {this.num =10; return 1}
var obj1 = new fn1()
console.log(obj1.num)    // 10

function fn2() {this.num =10; return []}
var obj2 = new fn2()
console.log(obj2.num)    // undefined

function fn3() {this.num =10; return null}
var obj3 = new fn3()
console.log(obj3.num)    // 10
/*
    new:
    1. 调用函数
    2. 自动创建一个对象
    3. 把创建出来的对象和this进行绑定
    4. 如果构造函数没有返回值,隐式返回this对象
*/
  • 箭头函数

本身没有this和arguments的,引用的this实际上调用的是定义的上一层作用域的this(对象不能形成独立作用域)

let _this = this
setTimeout(function(){console.log(_this)})
// 等价于
setTimeout(()=>console.log(this)) 

var obj1 = {num: 2, fn: () => console.log(this.num)}
obj1.fn()   // undefined,  this指向window
var obj2 = {num: 2, fn: () => console.log(this.num)}
obj2.fn()   // 2,  this指向obj2

修改this指向

var name = 'Char',age=17
var obj = {
    name: 'Wow',
    objAge: this.age,
    fn: function(fm,t){
        console.log(this.name + ' age ' + this.age + ' fron ' + fm + ' to ' + t)
    }
}
// call
obj.fn.call(item, 'Shanghai', 'Beijing')  // Job age 97 fron Shanghai to Beijing
// apply
obj.fn.apply(item, ['Shanghai', 'Beijing'])  // Job age 97 fron Shanghai to Beijing
// bind
obj.fn.bind(item, 'Shanghai', 'Beijing')()  // Job age 97 fron Shanghai to Beijing
obj.fn.bind(item, ['Shanghai', 'Beijing'])()  // Job age 97 fron Shanghai,Beijing to undefined