js中的this的使用笔记

在js的代码封装上this的应用是非常需要的,能够在调用的时候,可以让函数的获取变量环境动态的变化,这样在使用封装函数的时候可以切换所需要的变量环境,会更加的灵活,所以函数的this指向取决于调用的方式,而this的调用绑定绑定的方式一共分为四种

默认绑定

如果直接调用的函数this会指向全局

function test1() {
    console.log(this) // window全局对象
}
test1()

隐式绑定

通过某个对象进行调用的函数,会间接的将this绑定到了这个引用的对象上

function test2() {
    console.log(this) // obj对象
}
var obj = {
    name: "1",
    test2: test2
}
obj.test2()

显示绑定

使用call和apply、bind方法将需要this对象通过参数传入

function test3(a, b, c) {
    console.log(this, a, b,c) 
    // 1、obj对象 1 2 3
    // 2、obj对象 4 5 6
    // 3、obj对象 0 0 0
 }
 var obj = {
   name: "obj"
 }
test3.call(obj , 1,2,3)
test3.apply(obj , [4,5,6])
var test4 = test3.bind(obj, 0, 0 ,0)
test4()

new绑定

绑定到函数调用的this上,如果函数没有返回其他对象,表达式会返回这个新对象

function foo(number) {
    this.number = number
    console.log(this) // foo对象
}
  
var p1 = new foo(1)
console.log(p1.number) // 1

箭头函数

箭头函数是不绑定this的方法,本身箭头函数不绑定this,而是由该函数的外层作用域来决定this的指向。

绑定的优先级

默认绑定 < 隐式绑定、 bind绑定 < 显示绑定、new绑定 (call和apply不能同时使用所以不存在优先级的问题)

你可能感兴趣的:(js中的this的使用笔记)