夯实JS基础一this的指向问题和经典面试题

3次阅读

共计 1593 个字符,预计需要花费 4 分钟才能阅读完成。

很多高级编程语言都给新创建的对象分配一个引用自身的指针, 比如 JAVA、C++ 中的 this 指针,python 中的 self,JavaScript 也有 this 指针,虽然它的指向可能相对复杂些,但是this 指向的,永远只可能是对象

一、在一般函数方法中使用 this 指代 全局对象

function test(){
   this.x = 1
  console.log(this.x)
}
test()  // 1

二、. 作为对象方法调用,this 指代 上级对象,数组同理

var obj = {
    name:"obj",
    func1 : function() {console.log(this)
    }
}
obj.func1()  // this--->obj
document.getElementById("div").onclick = function(){console.log(this)
}; // this--->div

三、函数作为 window 内置函数的回调函数调用:this 指向window 对象(setInterval、setTimeout 等)

window.setInterval(function(){console.log(this)
}, 300)

四、作为构造函数调用,this 指代 new 实例化的对象

function test(){this.x = 1}
var o = new test()
alert(o.x)  // 1

五、apply、call、bind 改变函数的调用对象,此方法的第一个参数为改变后 调用这个函数的对象

var x = 0;
function test(){console.log(this.x)
}
var obj = {}
obj.x = 1
obj.m = test
obj.m.apply() //0,apply()的参数为空时,默认调用全局对象
obj.m.apply(obj); //1

六、匿名函数的执行环境具有全局性,this 对象通常指向window 对象

var name = 'The Window';
var obj = {
    name: 'My obj',
    getName: function() {return function() {console.log(this.name);
        };
    }
};

obj.getName()(); // 'The Window'

纸上得来终觉浅,绝知此事要躬行,一起动手刷一下 this 的经典面试题吧

var x = 3;
var y = 4;
var obj = {
    x: 1,
    y: 6,
    getX: function() {
        var x =5;
        return function() {return this.x;}();},
    getY: function() {
        var y =7;
         return this.y;
    }
}
console.log(obj.getX())//3
console.log(obj.getY())//6
 var name="the window";

 var object={
    name:"My Object", 
    getName:function(){return this.name;} 
 }

 object.getName();   //"My Object"

(object.getName)();   //"My Object"

(object.getName=object.getName)();   //"the window";
 var a=10; 
 var obt={ 
   a:20, 
   fn:function(){ 
     var a=30; 
     console.log(this.a)
   } 
 }
 obt.fn();  // 20

 obt.fn.call(); // 10

 (obt.fn)(); // 20

 (obt.fn,obt.fn)(); // 10

 new obt.fn(); // undefined
function a(xx){
  this.x = xx;
  return this
};
var x = a(5);
var y = a(6);

console.log(x.x)  // undefined
console.log(y.x)  // 6

< 题目持续更新中 …>

正文完
 0