执行以下选项中的程序,输出结果是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:"女",所以打印出女
关于super和class
子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。如果不调用super方法,子类就得不到this对象
var o ={ age:10, a:{ fn:function(){ console.log(this.age); } } } o.a.fn();//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 constructorB.子类Dog继承父类Animal Dog构造函数没加super()。报错
function fn(){ setTime(function(){ console.log(this); },100) } fn();//windowC.计时器中,this指向window,所以打印出来是window
var person={ sex:'女', fn:function(){ console.log(this.sex); } } person.fn()