javascript this的使用

this 其实是 call 方法的第一个参数,指向运行时环境绑定的对象

  • 作为对象的方法被调用, this 指向这个对象
const obj = {
    name : 'lili',
    say: function (){
        console.log(this === obj)
        console.log(this.name)
    }
}

obj.say() // 是以下调用方式的简写
obj.say.call(obj)
// 两者均输出 true lili
  • 作为普通函数调用,非严格模式,指向window;严格模式 undefined
this.name = 'global'
const say = function(){
    console.log(this === window) // true ,指向 window
    console.log(this.name)
}
say() // 是以下调用方式的简写
say.call(window)

'use strict'
this.name = 'global'
const say = function(){
  console.log(this === undefined)   // true , 指向 undefined
  console.log(this.name) // 报错
}
say() // 等同于 say.call(undefined)
this.name = 'global'
const obj = {
    name : 'lili',
    say: function (){
        console.log(this === window) 
        console.log(this.name)
    }
}
const winVar = obj.say; 
winVar() // true global
// winVar 作用域在window, 等同于 winVar.call(window)

'use strict'
this.name = 'global'
const obj = {
    name : 'lili',
    say: function (){
        console.log(this === undefined) // true , 指向 undefined
        console.log(this.name)
    }
}
const winVar = obj.say;
winVar() // 等同于 winVar.call(undefined)

  • 构造器调用,this指向new运算的实例对象;如果构造器显性的返回一个对象,this则指向这个对象。
function Person(){
    this.name = 'xiao w'
    this.say = function(){
        console.log(this.name)
    }
}
const man = new Person()
man.name = 'bob'
man.say() // bob
function Person(){
    this.name = 'xiao w'
    this.say = function(){
        console.log(this.name)
    }
    return {
        name: 'Person'
    }
}
const p = new Person()
p // {name: 'Person'}
  • call或apply调用,this指向第一个参数。

作用:1.改变this指向;2.允许一个对象调用另一个对象的方法和属性

  • 箭头函数

箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。

this.name = 'global'
const obj = {
    name : 'lili',
    say:  ()=>{
        console.log(this === window) // true ,指向 window
        console.log(this.name)
    }
}

obj.say() // true global
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值