4.this的原理以及几种不同使用场景的取值

1.this原理

this是JavaScript的一个关键字,函数调用时才会出现;
因为函数是在一定的环境中运行的,调用函数时肯定需要知道是[谁调用的]?就用到了this进行指向;
那么this到底指向的是什么?
this 既不指向函数自身,也不指函数的词法作用域,而是调用函数时的对象

2.使用场景

1.普通函数的调用,this指向的是Window

2.对象的方法,this指的是该对象

3.多层作用域链时,this指的是距离方法最近的一层对象

4.构造函数的调用,this指的是实例化的新对象

5.apply和call调用时,this指向参数中的对象

6.匿名函数调用,指向的是全局对象

匿名函数的三种方法

//①先用()包起来,然后再后面跟 (参数) 
(function(data){
  console.log(data);
})("222");
 
//②先后面跟(参数),然后再()包起来
(function(data){
  console.log(data);
}("333"));
 
//③正常函数格式,前面加 !
!function(data){
  console.log(data);

7.定时器中调用,指向的是全局变量

其实定时器的本质,也是一种匿名函数的形式。

 

8.箭头函数的this

箭头函数作为匿名函数,式不能作为构造函数的,不能使用new

箭头函数不绑定arguments,取而代之用rest参数…解决   

function A(a){
  console.log(arguments); //[object Arguments] {0: 1}
}
var B = (b)=>{
  console.log(arguments); //ReferenceError: arguments is not defined
}
var C = (...c)=>{ //...c即为rest参数
  console.log(c); //[3]
}
A(1);
B(2);
C(3);

箭头函数会捕获其所在上下文的this值,作为自己的this值

var obj = {
  a: 10,
  b: function(){
    console.log(this.a); //10
  },
  c: function() {
     return ()=>{
           console.log(this.a); //10
     }
  }
}
obj.b(); 
obj.c()();

箭头函数没有原型属性

3.this指向的优先级 ?

new>显式绑定>隐式绑定>默认绑定

默认绑定:默认函数指向wiindow

隐式绑定:object 箭头函数

显式绑定:apply call bind

new:构造函数

4.如何改变this指向?

三种方法:

call() 它可以调用函数也可以改变函数this的指向,一般用于继承

apply() 它也可以调用函数,也可以修改this指向,但他传递的参数必须在数组中呈现

bind()它不会主动调用函数,但是可以修改this指向,它返还的是原函数this指向改变之后的新函数

function fun() {
  console.log(this);  // 原来的函数this指向的是 Window
}
fun();
function fun(a, b) {
  console.log(this); // this指向了输入的 字符串apply
  console.log(a + b);
}
//使用apply() 方法改变this指向,
//此时第一个参数是 字符串apply,那么就会指向字符串apply
fun.apply('apply', [2, 3])  // 原函数的参数要以数组的形式呈现

bind() 方法的用法和call()一样,直接运行方法,需要注意的是:bind返回新的方法,

需要重新调用,是需要自己手动调用的

function fun() {
    console.log(this);  // 原来的函数this指向的是 Window
}

fun();
function fun(a, b) {
    console.log(this); // this指向了输入的 字符串bind
    console.log(a + b);
}

//使用bind() 方法改变this指向,此时第一个参数是 字符串bind,那么就会指向字符串bind
let c = fun.bind('bind', 2, 3);

c(); // 返回新的方法,需要重新调用

 

posted @ 2023-03-04 15:00  不想做混子的奋斗远  阅读(92)  评论(0)    收藏  举报