难受就摸头盖骨

javascript this指向和修改指向的方法

来源:Loong Panda

 

一、不同环境下的this的指向:

 

1、this的指向是在函数运行时确定下来的,而不是创建的时候,谁调用就指向谁。
2、ES5中普通函数this指向window,ES6中普通函数this指向为undefined;
3、事件的this指向,为事件源本身
4、定时器的this指向,为window.
5、构造函数内部的this指向new出来的这个对象

注: 严格模式下,普通函数和全局环境的this为undefined

 

1.1 普通函数和全局环境下this

consolog.log(this) // window

function test() { console.log(111, this) // window } test()

注: 'use strict' 严格模式下

consolog.log(this) // undefined
function test() { console.log(111, this) // undefined } test()

 

1.2对象中的this

 let obj3 = { 
   say() { 
     console.log(6666, this) // obj3 
     return function () { 
       console.log(7777, this) // window 
     } 
   } 
 } 
 obj3.say()()

1.3构造函数内的this

function Person(e) { 
  this.name = e console.log(5555, this) 
} 
let a = new Person('李四1') // Person { name: '李四1'} 
let b = new Person('李四2') // Person { name: '李四2'}

 

1.4定时器下的this

let obj2 = { 
  name: '张三', 
  say: function () { 
    console.log(333, this) // obj2 
    setTimeout(function () { 
      console.log(444, this) // window 
    }, 1000)
  } 
} 
obj2.say()

1.5箭头函数中的this

let obj3 = { 
  say() { 
    console.log(6666, this) // obj3 
    return () => { 
      console.log(7777, this) // obj3 
    } 
  } 
} 
obj3.say()()

 

二、改变this指向的方法:

1、箭头函数 -----> 只适合现代浏览器;
2、bind() -----> 第一个是参数是指向谁,第二个以后的参数是自定义的参数,需要单独调用才执行,如: bind(obj)()
3、call(xx, arg1, arg2) -----> 第一个是参数是指向谁,第二个以后的参数是自定义的参数
4、apply(xx, [arg1, arg2]) -----> 第一个是参数是指向谁,第二个的参数是自定义的参数,数据类型必须是数组

 

例子

function test(arg1, arg2) { 
  console.log(111, `都${this.age}了,${arg1}${arg2}`) 
} 
let obj = { 
  age: 18 
} 

test('该闭眼睛了!', '不然就没地方埋了') // 都undefined了,该上坟了! 
test.call(obj, '该嫁人了!', '不然以后你儿子坐公交车就只能和老奶奶聊天了') // 都18了,该嫁人了!不然以后你儿子坐公交车就只能和老奶奶聊天了 
test.apply(obj, ['该离婚了!', '不然其他光棍怎么会有对象呢']) // 都18了,该离婚了!不然其他光棍怎么会有对象呢
test.bind(obj, '该退休了!', '不然钱没花完,人先走了')() // 都18了,该嫁人了!不然以后你儿子坐公交车就只能和老奶奶聊天了

 

posted @ 2022-04-09 16:11  longpanda_怪怪哉  阅读(124)  评论(0编辑  收藏  举报
下定决心了,要把写不出代码就摸后脑勺的习惯给改了! 如果可以~单身待解救~~