主页

全局作用域或者普通函数中this指向全局对象window( 注意定时器里面的this指向window)

console.log(this) // this指向window

function fn() {
    console.log(this)
}
fn() // this指向window

setTimeout(function () {
    console.log(this) // this指向window
}, 1000)

方法调用中谁调用this指向谁

let o = {
    sayThis: function () {
        console.log(this)
    }
}
o.sayThis() // this指向o这个对象

    btn.onclick = function () {
    console.log(this) // this指向btn
}

btn.addEventListener('click',function() {
    console.log(this) // this指向btn
})

构造函数中this指向构造函数的实例

function Fun() {
    console.log(this)
}
let fun = new Fun() // this指向fun实例对象
// 在函数中直接使用
function get(content) {
  console.log(content)
}
get('你好')
// get.call(window, '你好')

// 函数作为对象的方法被调用(谁调用我 我就指向谁)
var person = {
  name: '张三',
  run: function (time) {
    console.log(`${this.name} 在跑步,最多${time}min 就不行了`)
  }
}
person.run(30)
// person.run.call(person, 30)
var name = 222
var a = {
  name: 111,
  say: function() {
    console.log(this.name)
  }
}

var fun = a.say
fun()                  // fun.call(window) // 222

a.say()                // a.say().call(a) // 111

var b = {
  name: 333,
  say: function(fun) {
    fun()              
  }
}

b.say(a.say)           // fun.call(window) // 222
b.say = a.say
b.say()                // b.say.call(b) // 333

JavaScript

版权属于:Joe
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
0

目录

来自 《JS-this指向问题》
评论

qiaofugui

博主很懒,啥都没有
188 文章数
14 评论量
3 分类数
191 页面数
已在风雨中度过 2年137天13小时41分