this到底是什么,this指向其所在函數的直接調用者!!!


this指向其所在函數的直接調用者。this在函數中使用,函數都有掛載的對象,沒有明確掛載到對象上的函數,默認都掛着在window對象上。

一定要明確是誰調用了函數,this就指向這個調用者。

一般很常見的就是函數

此時的this是瀏覽器的window對象,函數默認聲明到window對象上,函數在瀏覽器中執行,在其中引用this,this即為window對象

function  fThis(){
   console.log(this)
}
fThis();

 

 this是指當前匿名對象

$.easyui = { indexOfArray: function(a, o, id){ for(var i=0,len=a.length; i<len; i++){ if (id == undefined){ if (a[i] == o){return i;} } else { if (a[i][o] == id){return i;} } } return -1; }, addArrayItem: function(a, o, r){ var index = this.indexOfArray(a, o, r ? r[o] : undefined); if (index == -1){ a.push(r ? r : o); } else { a[index] = r ? r : o; } } }

 

此時的this是指數組r中的元素


function a
(){ var r = $('div'); r.each(function(){ console.log(this); }) }

 

 此時的this指的是$,即jQuery, tabs是jQuery的屬性,函數是其值,調用函數的本體就是$

$.fn.tabs = function(options, param){
        
        console.log(this);
};

$.fn.tabs();

 

此時的this指的是tabs
$.fn.tabs = function(options, param){
        
        this.each(function(){
            console.log("a")
        })
    };
    
    $.fn.tabs();
    
    
jQuery.fn = jQuery.prototype = {
    
    each: function( callback ) {
        return jQuery.each( this, callback );
    }
    
}    

jQuery.extend({
    each: function( obj, callback ) {
        var length, i = 0;

        if ( isArrayLike( obj ) ) {
            length = obj.length;
            for ( ; i < length; i++ ) {
                if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
                    break;
                }
            }
        } else {
            for ( i in obj ) {
                if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
                    break;
                }
            }
        }

        return obj;
    }
});

 

函數的幾種執行方式:
1、匿名函數直接執行,this = window
(function(){
console.log(this);
})(this);
2、函數名調用執行,this = window
function a(){
console.log(this);
}
a();
3、通過函數聲明為類方法,this = User, this指向類,使用this只能調用類的類成員,不能調用實例成員
function User(){}
User.getName = function(){
console.log(this);
}
User.getName();
4、函數聲明為類實例方法,this = Object 即類的實例, this指向類對象,使用this只能調用類的實例成員,不能調用實例成員
function User(){}
User.prototype.getName = function(){
console.log(this);
}
var user = new User();
user.getName();

5、一個對象調用另個一對象的函數


6、一個類調用另一個類的函數
function User(){}
User.prototype.getName = function(callback){
this.start(callback);
}

function DriverCar(){}
User.prototype.start = function(callback){
this._start(this, callback);
}
User._start = function(obj, callback){
console.log("DriverCar _start: " + obj);
callback();
}
User.getName(function(){
console.log("boot");
});

function Test(){}
Test.test = function(){
User.getName(function(){
console.log("start : " + this);
});
}
Test.test();

 

 


免責聲明!

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



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