有关js基础 this指向问题和解析

90 阅读1分钟

this指向要在执行时才能确认值,定义时无法确认;

var a = {
    name: 'A',
    fn: function(){
        console.log(this.name)
    }
}
a.fn()  // this指向a这个对象,谁调用指向谁
a.fn.call({name:'B'}) // this指向 {name: 'B'}
var fn1 = a.fn;
fn1(); // this指向widonw对象

js不是编译型语言,是解释型语言

this的几种执行场景:

  1. 作为构造函数执行,this指向该构造函数
  2. 作为对象属性执行,this指向该对象
  3. 作为普通函数执行,this指向window对象
  4. call/apply/bīnd
关于第四条说明
function fn1(name,age){
    console.log(this);// {'name':'list'},this指向该对象
}
fn1.call({name:'lisi'},'zhangsan','20')
var fn2 = function(name,age){
    console.log(this) // {'name':'list'},this指向该对象
}.bind({'name':'lisi'})
fn2('zhangsan','20')
eg:bind必须放在函数表达式后面,函数声明会报错
当该对象为null或者undefined --->this指向window对象