2014-09-25 71 views
0

我有這樣的代碼:檢查包裝函數是否被調用?

function Q(a){ 
    function cElems(e,f,p){var l=e.length,i=0;if(e instanceof Array){while(i<l){f(e[i],p);i++}}else{f(e,p)}} 
    if(typeof a=="string"){ 
    var b=a[0],c=a.substr(1),r=[].slice.call(document.getElementsByClassName(c)); 
    return{ 
     setClass:function(b){cElems(r,function(e,p){e.className=p},b)} 
    }; 
    } 
} 

我要檢查,如果包裝的函數被調用,即:Q(".test").setClass("test2"),如果沒有返回不同的東西,比如:

if(wrapped==true){ 
    return{ 
    setClass:function(b){cElems(r,function(e,p){e.className=p},b)} 
    }; 
}else{ 
    return "no constructor was called"; 
} 

這可能嗎?

+0

你試過了嗎? – andrex 2014-09-25 01:22:01

+0

試過了什麼?我的第二個代碼是僞代碼,沒有'wrapped'變量。 – 2014-09-25 01:23:55

+0

這個問題還不清楚 - 在這種情況下什麼是「包裝功能」?請注意,在Q(..)。x'中,總是在解析'x'之前調用'Q(..)'。 – user2864740 2014-09-25 01:26:29

回答

1

Q(..).x()Q(..)總是調用之前x被解決(和調用);這可以清楚地看到與重寫它這樣:

var y = Q(..); // this executes and the value is assigned to y 
y.x();   // and then the method is invoked upon the object named by y 

因此,它是不可能改變基於調用Q(..).x的結果的Q(..)已經執行的行爲 - 對象具有已經Q(..)返回。

+0

那麼jQuery如何做到這一點?調用'$(「。class」)'返回一個元素數組,其中'$(「。class」).hover(function)'做了一些不同的事情。 – 2014-09-25 01:31:31

+0

jQuery對象'$(「。class」)'的結果沒有改變。相反,jQuery然後將懸停事件添加到所有匹配的項目,這些項目作爲從$(..)*返回的jQuery對象的內部狀態的一部分存在。 – user2864740 2014-09-25 01:31:59

+0

確實沒有,但是我不能在jQuery之外調用'element.hover()'我怎樣才能做出這樣的「子函數」? – 2014-09-25 01:33:56

0

你可以看到,如果一個函數被調用,就像這樣:

var costructoed = 0; 
function Constructo(){ 
    constructoed = 1; 
} 
function whatever(func){ 
    if(constructoed){ 
    func('It worked!'); 
    } 
    else{ 
    func('Constructo was not executed'); 
    } 
} 
whatever(console.log); 
Constructo(); 
whatever(console.log); 

查看一個構造函數的方法是否已經執行它像:

function Constructo(){ 
    this.someValue = 0; 
    this.someMethod = function(){ 
    this.someValue = 1; 
    } 
    this.someMethodWasExecuted = function(func){ 
    if(this.someValue === 1){ 
     console.log('someMethod was executed'); 
    } 
    else{ 
     func(); 
    } 
    } 
} 
function whenDone(){ 
    console.log('someMethod was not Executed whenDone ran instead'); 
} 
var whatever = new Constructo; 
console.log(whatever.someMethodWasExecuted(whenDode)); 
whatever.someMethod(); 
console.log(whatever.someMethodWasExecuted(whenDode));