非严格模式下,this有4种绑定机制(默认、隐式、显式、new)

发布时间 2023-11-16 11:04:18作者: 龙陌

执行以下选项中的程序,输出结果是undefined的是()

A

var o = {

age: 18,

a: {

fn: function(){

console.log(this.age);

}

}
}
o.a.fn();

B

class Animal{
  constructor(color){
    this.color = color;
  }

  getColor(){
    console.log("animal的颜色是" + this.color);
  }
}

class Dog extends Animal{
  constructor(color){
    this.color = color;
  }
}

var dog = new Dog("黄色");
dog.getColor();

C

function fn(){

setTimeout(function(){

console.log(this);

},100)

}

fn();

D

var person = {

sex:"女",

fn: function(){

console.log(this.sex);

}

}

person.fn()

正确答案:A

谁调用this,this指向谁

A.o.a.fn(); 是a在调用,指向a,但是a没有age这个属性,所以为undefined
B.子类Dog继承父类Animal Dog构造函数没加super()。报错
ES6 class规定必须在子类调用super,因为子类的this是由父类得来的
C.fn(), 默认绑定,指向window,也可以看做是window.fn(),所以this打印出来是window
D.person.fn(); person在调用,this指向person,person对象的属性sex:"女",所以打印出女

非严格模式下,this有4种绑定机制(默认、隐式、显式、new)

默认就是fn()的形式,无论在哪个位置,只要是fn()都是指向window
隐式就是obj.fn的形式,只看fn前面1个,obj1.obj.fn 还是obj在调用而不是obj1,
显式就是通过call、apply、bind强行改变this的指向,
new指向创建的对象

关于super和class

子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象