关于javascript:this到底指向什么记住这4点就够了

2次阅读

共计 1538 个字符,预计需要花费 4 分钟才能阅读完成。

本文次要在于把握 this 在 JavaScript 的指向,理解 this 是在什么时候确定的,谁决定了 this 的指向。

4 大规定

优先级权重:顺次 从上到下 ,权重值 从小到大

  1. (优先级最小)默认绑定规定:console.log(this === window); // true
  2. (优先级次于后两项)隐式绑定规定:谁调用就指向谁;(隐式失落)。
  3. (优先级次于 new 绑定)显示绑定规定:call,apply,bind。
  4. (优先级最大)new 绑定规定。

this 的默认绑定规定

全局的 this 默认指向 window, 如果开启严格模式的话,则 this 指向 undefined。

• 例子 1:

console.log(this === window) // true 严格模式下全局的 this 为 undefined
console.log({} === {}) // false
  1. this 和 window 之所以输入的是 true, 是因为他们指向的是同一个地址;
  2. 两个对象为什么不相等呢,次要是因为,对象比照的是指针地址,每申明一个对象就开拓一个空间生成一个指针地址指向存数据的中央。

this 的隐式绑定规定

如果办法是通过某个对象点的办法调用的话,则 this 指向调用的对象,如果是间接调用(自主调用)的话,则 this 指向 window.

• 例子 1:

function test(){console.log(this === window); // true
}
test() // 能够了解为 window.test();
  1. 函数的独立调用,其实就是相当于 window.xxx()的形式调用,因为全局申明的函数都是默认挂载到 window 上的,所以 this 也默认指向 window。

• 例子 2:

var obj = {
    a: 2,
    foo: function(){console.log(this); // obj
        function test(){console.log(this); // window
        }
        test();}
}
obj.foo();
  1. 因为 foo 是 obj 调用,所以 foo 函数的 this 应该指向调用他的对象,所以外部打印进去的 this 为 obj;
  2. 而 test 尽管是在 foo 的外部调用,然而属于间接调用所以 this 仍旧指向 window。

this 的显示绑定规定

如果通过 call,apply,bind 强制更改 this 指向,则 this 指向办法传入的第一个参数。

• 例子 1

var name = 'test1'
var obj = {name: 'test2'}
function fn(){console.log(this.name);
}
var bindFn = fn.bind(obj);
bindFn() // test2
fn.call(obj) // test2
fn.apply(obj) // test2
  1. 因为应用了 call,apply,bind 强行更改了 this 指向,所以 this 指向传入的第一个参数(obj)。

this 的 new 绑定

  1. 如果构造函数外部没有返回援用类型变量,则构造函数外部会创立一个新的对象,this 就是这个对象;
  2. 如果构造函数外部返回了援用类型变量,则 this 为返回的这个对象。

• 例子 1:

function Body(){console.log(this); // Body {}}
new Body()
function Person(){console.log(this); // {name: "test"}
  return {name: 'test'}
}
new Person()
  1. 因为 Body 外部没有返回援用类型的数据所以 this 指向新创建的对象,Person 构造函数外部返回了一个对象,所以 this 则指向返回的对象。

总结:

在 js 中函数定义时,this 的指向是不确定的,只有在执行的时候,能力确定 this 的指向,所以能够总结成一句话,this 指向是依据执行调用时的动静上下文来决定的

正文完
 0