检查是否调用了包装函数

Check if wrapper function is called?

本文关键字:包装 函数 调用 是否 检查      更新时间:2023-09-26

我有这个代码:

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

这可能吗?

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(..)返回

您可以查看是否调用了函数,如下所示:

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));