this的指向问题

this的指向问题

  1. 使用对象调用函数时(函数为对象上的属性),谁调用this就指向谁
let obj = {
    test:function(){
        console.log(this)
    },
    arrowTest:()=>{},
    test2:function(){
        console.log(this)
        function temp(){
        	console.log(this)
        }
    },
}
obj.test() // 指向obj {test: ƒ}
  1. 使用new 调用构造方法时,this为新创建的对象,原型链指向方法的prototype,constructor为调用的构造方法
new obj.test() //test {}
  1. 直接调用的函数,this指向window
//例一
let func1 = obj.test;
func1()// 指向window
// 例二
obj.test2();
// 第一个this 为obj
// 第二个this输出为 window

  1. call apply bind 可以改变this的指向,this为指定的对象,指定的对象为null时,this指向window
obj.test.call({})// 指向{}
obj.test.apply({})// 指向{}
let bindfunc = obj.test.bind({})
bindfunc()// 指向{}

如果指定的对象为null 或者 undefined 或者不传,则this指向window

obj.test.call()// 指向window
obj.test.apply()// 指向window
let bindfunc = obj.test.bind()
bindfunc()// 指向window
obj.test.call(null)// 指向window
obj.test.apply(null)// 指向window
let bindfunc = obj.test.bind(null)
bindfunc()// 指向window
obj.test.call(undefined)// 指向window
obj.test.apply(undefined)// 指向window
let bindfunc = obj.test.bind(undefined)
bindfunc()// 指向window

如果指定对象为基本类型,会在绑定时调用基本类型的构造方法,构造出一个基本类型对象

obj.test.call(1)// 指向Number {1}
obj.test.apply(1)// 指向Number {1}
let bindfunc = obj.test.bind(1)
bindfunc()// 指向Number {1}
  1. 箭头函数的this指向声明箭头函数的作用域,不是谁调用指向谁。
    箭头函数没有arguments this new.target 它的这些参数指向定义时作用域的arguments this new.target,如果定义的环境没有arguments new.target,使用arguments new.target会报错
    箭头函数没有原型
    使用场景:匿名函数(事件处理,异步方法),不想改变this指向,代码简洁性
obj.arrowTest()// 指向window
obj.test.arrowTest({})// 指向window
obj.test.arrowTest({})// 指向window
let bindfunc = obj.test.arrowTest({})
bindfunc()// 指向window
  1. dom事件的this指向监听的事件的dom元素
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no,maximum-scale=1">
    <style>
    #main{
    	height:400px;
    }
    </style>
</head>
<body>
<div id="main"><span>3423424242</span><br><span>3423424242</span><br><span>3423424242</span><br><span>3423424242</span><br><span>3423424242</span></div>
<script>
document.getElementById('main')
	.addEventListener('click',
						function(){
							console.log(this)// this为document.getElementById('main')节点
						})
</script>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值