#this!

什么是this?

很多高級編程語言都給新創(chuàng)建的對象分配一個引用自身的指針,比如JAVA、C++中的this指針,python中的self,JavaScript也有this指針,雖然它的指向可能相對復(fù)雜些,但是this指向的,永遠只可能是對象。

一、在一般函數(shù)方法中使用 this 指代全局對象。
function test(){
   this.x = 1
  console.log(this.x)
}
test()  // 1
二、作為對象方法調(diào)用,this 指代上級對象,數(shù)組同理、
var obj = {
    name:"obj",
    func1 : function() {
        console.log(this)
    }
}
obj.func1()  // this--->obj;
document.getElementById("div").onclick = function(){
   console.log(this)
}; // this--->div
三、函數(shù)作為window內(nèi)置函數(shù)的回調(diào)函數(shù)調(diào)用:this指向window對象(setInterval、setTimeout 等)
setInterval(function(){
  console.log(this)//window
}, 300)
四、作為構(gòu)造函數(shù)調(diào)用,this 指代 new 實例化的對象
function test(){
  this.x = 1
}
var o = new test()
alert(o.x)  // 1
五、apply、call、bind改變函數(shù)的調(diào)用對象,此方法的第一個參數(shù)為改變后調(diào)用這個函數(shù)的對象
var x = 0;
function test(){
  console.log(this.x)
}
var obj = {}
obj.x = 1
obj.m = test
obj.m.apply() //0,apply()的參數(shù)為空時,默認調(diào)用全局對象
obj.m.apply(obj); //1
六、匿名函數(shù)的執(zhí)行環(huán)境具有全局性,this對象通常指向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",函數(shù)賦值會改變內(nèi)部this的指向,這也是為什么需要在 React 類組件中為事件處理程序綁定this的原因;
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容