this面试题

时间:2020-12-21 02:26:55

// 考题1
/*function Fn() {
console.log(this);//window
}
Fn();
new Fn();//Fn实例
Fn.apply(Fn); //将this指向Fn,所以输出function Fn(){console.log(this)}

/*---------------------------------------------------------*/

// 考题2
/*var o = {
f : function () {
console.log(this);
},
2 : function () {
console.log(this);
}
};
o.f();//o
o[2]();//o
new o[2]();//new出来的新实例
o.f.call([1,2]);/[1,2](更改了this指向)
o[2].call([1,2,3,4]);*///[1,2,3,4]

/*---------------------------------------------------------*/

/*var name ='out';
var obj ={
name:'in',
prop:{
name:'inside',
getName:function(){
return this.name;
}
}
};
console.log(obj.prop.getName());
var test = obj.prop.getName;
console.log(test());
console.log(obj.prop.getName.apply(this));*/

/*-------------------------------------------------------*/

// 考题3
/*var length = 10;
function fn() {
console.log(this.length);
}
var obj = {
length: 5,
method: function (f) {
f();//10
// arguments[0] 可以获取到传入method方法的第一个实参
arguments[0]();//1  (arguments是一个伪数组对象,他的第一个参数是fn函数,他调用fn函数,所以this指的是arguments)
arguments[0].call(this);//5(改变fn的指向,这里的this是method)
}
};
obj.method(fn);*/

/*---------------------------------------------------------*/

// 考题4
var scope = 'global';
function log() {
console.log(this.scope + ':' + arguments[0]);
}
var dog = {
scope : 'dog',
yelp : function () {
var scope = 'dog.yelp';
log('wow');
}
};

dog.yelp();//global:wow
dog.yelp.apply(dog);//global:wow
log.call(dog, 'created');//dog:created

/*---------------------------------------------------------*/