简体   繁体   English

检查包装器函数是否被调用?

[英]Check if wrapper function is called?

I have this code: 我有以下代码:

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

I want to check if a wrapped function is called, ie: Q(".test").setClass("test2") , and return something different if not, like so: 我想检查是否调用了包装函数,即: 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";
}

Is this possible? 这可能吗?

In Q(..).x() , Q(..) is always invoked prior to x being resolved (and invoked); Q(..).x()Q(..) 总是x被解析(并被调用)之前被调用; this can be clearly seen with rewriting it as so: 这样重写就可以清楚地看到:

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

Thus it is not possible to alter the already-executed behavior of Q(..) based on the result of invoking Q(..).x - the object has already been returned from Q(..) . 因此,不可能基于调用Q(..).x的结果来更改Q(..)的已执行行为-对象已经Q(..)返回。

You can see if a function has been invoked, like so: 您可以查看是否已调用函数,如下所示:

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

To see whether a method in an Constructor has executed it's like: 要查看构造函数中的方法是否已执行,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM