JS中 this 的四種用法


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

function fn(){
    this.x = 1 } fn(); //相當於window.fn() 

2、作為對象方法使用 this 指該對象

function fn(){
    alert(this.x) //this是調用該函數的obj對象 輸出test
} var obj = {'fn':fn,'x':'test'} obj.fn(); 

3、作為構造函數使用 this 指new 函數出的對象

function fn(){
    this.x = 123; //this是調用該函數的obj對象
} var obj = new fn(); //obj = {x:123}

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

var x = 11;
function fn(){ alert(this.x) } var obj = {'fn':fn,'x':22} var obj2 = {'x':33} obj.fn.apply(); // 11 ,apply()參數為空時,默認調用的是全局對象,this當前指全局對象 obj.fn.apply(obj); // 22 obj.fn.apply(obj2); // 33

 


免責聲明!

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



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