JS中的this是什么,this的四種用法


在Javascript中,this這個關鍵字可以說是用的非常多,說他簡單呢也很簡單,說他難呢也很難,有的人開發兩三年了,自己好像也說不清this到底是什么。下面我們來看看:

1、在一般函數方法中使用 this 指代全局對象

function hello(){
   this.x = 1;
   console.log(this.x)
}

hello();
//此時控制台打印1

2.作為對象方法調用,this 指代上級對象

function hello(){
   console.log(this.x)
}

var s = {};
s.x = 1;
o.m = hello;
o.m();
//此時控制台打印1

3.作為構造函數調用,this 指代new 出的對象

function hello(){
   this.x = 1;
}

var s = new hello();
console.log(s.x)
//運行結果為1,為了表明這是this不是全局對象,我們對代碼做一些改變

var x = 2;
function hello(){
   this.x = 1;
}

var o = new hello();
console.log(x)

4.apply 調用 ,apply方法作用是改變函數的調用對象,此方法的第一個參數為改變后調用這個函數的對象,this指代第一個參數

var x = 0;
function hello(){
   console.log(this.x)
}

var h = {};
h.x = 1;
h.m = hello;
h.m.apply();  //輸出為0

h.m.apply(h) //輸出1

以上就是常用的四種方法,大家要是不明白,可以把demo運行一下自己就知道了。

以上部分內容來自網絡,有問題可以在下面評論,技術問題可以在私聊我。

技術QQ群:213365178


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM