简单聊聊js 里的 this <this的指向>

这是我参与新手入门的第1篇文章
新人报道,请多多关照

this.png

默认绑定

被自身调用时,this指向window 在浏览器(js)环境中,立即执行函数 中this ===window
在浏览器中,this === window;

console.log (this === window); // true
function test(){
    console.log(this === window); // true
}
test() 
// test 直接被调用
复制代码

隐式绑定

  1. 当前的对象调用,被谁调用,this 指向谁.(形式如obj.function())
  2. 当函数独立调用(自身直接调用)时,this 指向window.
  3. 隐式丢失,导致 this绑定失败,还是指向了window
var a =0;
var obj ={
    a:3,
    foo:function(){
        console.log(this) // 指向obj , obj调用
        function test(){
            console.log(this)
            // 指向window ,当函数独立调用(自身直接调用)时,this 指向window
        }
        test();
    }
}

obj.foo();
复制代码

隐式丢失

变量赋值

function foo(){
    console.log(this) // this === window 
}

var obj ={
    foo:foo
}

var bar = obj.foo;
bar() 

复制代码

参数赋值

function foo(){
    console.log(this) // this === window 
}
var b = 2;
var obj={
 b :3, 
 foo:foo
}
function bar(fn){
    console.log(this) // this === window
    fn()
}
//预编译的过程中,实参被赋值为形参 (值的拷贝过程->浅拷贝的过程)
bar(obj.foo) 
复制代码

显示绑定

  • 父函数有能力更改子函数的this 指向 (call,bind,apply)
  • 使用 call 和 apply 时,如果用作 this 的值不是对象,则会被尝试转换为对象。null 和 undefined 被转换为全局对象。
  • 调用f.bind(someObject)会创建一个与f具有相同函数体和作用域的函数,但是在这个新函数中,this将永久地被绑定到了bind的第一个参数,无论这个函数是如何被调用的。
function foo(){
    console.log(this)
}
var obj={
    foo:foo,
}
var bar = obj.foo;   // this === window 
obj.foo() // this === obj
bar.call(obj) // this === obj  传参形式 bar.call(obj,1,2,3,)
bar.apply(obj) // this === window  传参形式 bar.apply(obj,[1,2,3])
bar.bind(obj)() //  this === window 传参形式 bar.bind(obj)(1,2,3,4)  


注 bind 只生效一次,
var test ={
a:2
}
eg: bar.bind(test)() // this === obj, 不指向test
复制代码

new 绑定

  1. 指向它的实例化对象
  2. 返回引用类型时,则会改变this 指向返回的引用类型
function Person(){
    this.a= 1;
}

const person = new Person();
console.log(person) // 指向它的实例化对象

function Person(){
    this.a= 1;
    // return 引用类型时,this 指向返回的引用类型
    return [1,3]
}

const person = new Person();
console.log(person) // 指向[1,3]的地址
复制代码

箭头函数

箭头函数中,被谁调用,this 指向谁。
在全局代码中,它将被设置为全局对象。

var obj = {
    bar: function() {
      var x = (() =>{ 
        console.log('--',this)
        return this
        });
      return x;
    }
  };
  // 作为obj对象的一个方法来调用bar,把它的this绑定到obj。
  // 将返回的函数的引用赋值给fn。
  console.log(obj.bar()()) // this 指向bar
   var fn2 = obj.bar;  // 类似隐式绑定里的变量赋值,隐式丢失,可发散思维思考一下
  // 那么调用箭头函数后,this指向window,因为它从 bar 继承了this。
  console.log(fn2()() == window); // true
复制代码

总结

在绝大多数情况下,函数的调用方式决定了 this 的值(运行时绑定)。this 不能在执行期间被赋值,并且在每次函数被调用时 this 的值也可能会不同。

以上有关this的讨论皆为在非严格模式下进行的讨论

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享