检查是否调用了包装函数
Check if wrapper function is called?
我有这个代码:
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));
相关文章:
- 如何使用图表包装函数有条件地格式化谷歌可视化表单元格
- 从原型更改/包装函数
- 我正在尝试使用 html 元素包装函数的返回值
- 将 ajax .done 作用域扩展到包装函数
- 在javascript中需要帮助包装函数并正确处理“this”
- 包装函数后无法读取属性
- 检查是否调用了包装函数
- 从生成器函数中包装co和co-mysql,并从包装函数中让步
- 窗口对象上具有全局变量的包装函数
- 使用removeEventListener删除包装函数回调
- 用JavaScript正确包装函数
- 如何从包装函数返回javascript ajax调用的结果
- 如何包装函数调用,有时做异步调用,使其行为同步
- 为什么UnderscoreJS有很多原生Javascript函数的包装函数?
- Knockout - keyCode属性没有通过包装函数传递
- Highcharts包装函数'
- 中间javascript: ajax请求的包装函数稍后执行主函数
- 是否有一种聪明的方法来访问包装函数中的变量
- Jquery新手在包装函数时遇到问题
- express 4的异步包装函数没有't捕获错误