this

this绑定原则

1.默认绑定

默认绑定是函数针对的独立调用的时候,不带任何修饰的函数引用进行调用,非严格模式下 this 指向全局对象(浏览器下指向 Window,Node.js 环境是 Global ),严格模式下,this 绑定到 undefined ,严格模式不允许this指向全局对象。

var name = 'hello'
var obj = {
    name : 'test',
    foo: function() {
        console.log(this.name )
    }
}
var bar = obj.foo
bar()   // hello

在函数中以函数作为参数传递,例如setTimeOut和setInterval等,这些函数中传递的函数中的this指向,在非严格模式指向的是全局对象。
注意为箭头函数时指向外层对象调用作用域

var name = 'window';
var person = {
    name: 'person',
    sayHi: sayHi,
    sayHi2:function(){
       setTimeout(()=>{
         console.log(this.name);
       })
    }
}
function sayHi(){
    setTimeout(function(){
        console.log(this.name);
    })
}
person.sayHi();  //window
person.sayHi2();  //person

隐式绑定

判断 this 隐式绑定的基本标准:函数调用的时候是否在上下文中调用,或者说是否某个对象调用函数

var name = 'hello'
var obj = {
    name : 'test',
    foo: function() {
        console.log(this.name )
    }
}
obj.foo()  //hello

当有多层对象嵌套调用某个函数的时候,如 对象1.对象2.函数,this 指向的是最后一层对象(对象2)。

显式绑定

call apply
bind bind 方法 会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。

new 绑定

function Person(name){
   this.name = name;
   this.test=function(){
       console.log(this.name)
   }
}
var person= new Person('test');
console.log('Hello,', person.name);  //test
console.log(person.test())  //test

this优先级

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

箭头函数中的this

箭头函数中this直接指向的是调用函数的上一层运行时
this指向的是当前函数的词法作用域

箭头函数表达式的语法比函数表达式更短,并且不绑定自己的this,arguments,super或 new.target。这些函数表达式最适合用于非方法函数(non-method functions),并且它们不能用作构造函数。
箭头函数中没有 arguments
没有构造函数
没有原型 prototype 是
箭头函数中没有自己的this

var a = 'test'
let obj = {
    a: '程序员成长指北',
    foo: () => {
        console.log(this.a)
    },
    test:function (){
       this.foo()
    } 
}
obj.foo()   //test
obj.test()  //test

call、apply、bind无法改变箭头函数this指向

var test=()=>{console.log(this)}
var obj={a:'a'};
test.call(obj)// window

this面试题

var length = 10;
function fn() {
    console.log(this.length);
}
var obj = {
  length: 5,
  method: function(fn) {
    fn();  //调用的时候没有任何修饰符
    arguments[0]();  //arguments修饰符
  }
};
obj.method(fn, 1); // 10  2
var a=10;   
function test(){  
   a=5;      
   console.log(a);   
   console.log(this.a);    
   var a;      
   console.log(this.a);   
   console.log(a);   
 }

test()  //5  10  10 5  this指向window
new test()  //5,undefined,undefined,5    this指向test

来源

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容