检查是否调用了包装函数?

时间:2014-09-25 01:19:20

标签: javascript function

我有这段代码:

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";
}

这可能吗?

2 个答案:

答案 0 :(得分: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(..)的结果更改Q(..).x已执行的行为 - 该对象已从<{1>返回 }}

答案 1 :(得分: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));