首页 > 试题广场 >

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

[单选题]

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


  • var o = {

    age: 18,

    a: {

    fn: function(){

    console.log(this.age);

    }

    }
    }
    o.a.fn();
  • 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();

  • function fn(){

    setTimeout(function(){

    console.log(this);

    },100)

    }

    fn();

  • var person = {

    sex:"女",

    fn: function(){

    console.log(this.sex);

    }

    }

    person.fn()

谁调用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对象

发表于 2021-12-12 11:16:41 回复(7)
var o ={
    age:10,
    a:{
        fn:function(){
            console.log(this.age);
        }
    }
    }
    o.a.fn();//undefined
       A.o.a.fn(); 是a在调用,指向a,但是a没有age这个属性,所以为undefined
    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();//Uncaught ReferenceError: Must call super constructor in derived
                  // class before accessing 'this'&nbs***bsp;returning from derived constructor
B.子类Dog继承父类Animal Dog构造函数没加super()。报错
function fn(){
        setTime(function(){
            console.log(this);
        },100)
    }
    fn();//window
C.计时器中,this指向window,所以打印出来是window
 var person={
        sex:'女',
        fn:function(){
            console.log(this.sex);
        }
    }
    person.fn()

D.person.fn(); person在调用,this指向person,person对象的属性sex:"女",所以打印出女
发表于 2022-06-25 12:22:46 回复(0)
说明下不是严格模式比较好,扫一眼看到C,就选了。结果错了。
发表于 2022-04-14 11:46:58 回复(0)
就是谁调用,this指向就是谁
发表于 2022-12-01 10:27:09 回复(0)
非对称加密
发表于 2022-05-29 09:12:18 回复(0)
A,严格模式下C也是
发表于 2022-03-13 08:36:11 回复(2)