I want to be able to tell if a function is noop. I was looking for a built in method such as angular.isNoop() but couldn't find anything. Is there anything that differentiates a noop?
I want to be able to tell if a function is noop. I was looking for a built in method such as angular.isNoop() but couldn't find anything. Is there anything that differentiates a noop?
Share Improve this question edited Oct 14, 2015 at 19:02 Estus Flask 224k79 gold badges472 silver badges611 bronze badges asked Oct 14, 2015 at 18:25 ialexanderialexander 91010 silver badges28 bronze badges 1- well, if you're getting the noop from a shared location, they'd all contain the same function, thus allowing you to do an exactly equals check. Otherwise all you can do is look at the .toString() of the function. – Kevin B Commented Oct 14, 2015 at 18:29
3 Answers
Reset to default 3A noop is simply a function that contains no operations. You can test for a specific noop function by using ===
For example;
console.log(x === angular.noop);
Will print true if x
was assign the noop from Angular, but this will not work if x
is using the noop from jQuery.
To check if a variable looks like a noop. You just need to see if the function string ends with {}
. You can try something like this.
console.log(angular.isFunction(x) && /\{\}$/.test(x.toString()));
The above should work even in the code is minified.
A noop function has a name just like any other function. That name is noop
. So you can check for it just by calling:
var theFunction = angular.noop;
theFunction.name === 'noop'
It is not a typical task, it is unlikely that the framework will have one.
function isNoop(fn) {
var trimRegex = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
try {
return !fn.toString().match(/{([\s\S]*)}$/)[1].replace(trimRegex, '');
} catch (e) { };
}
It does not check for noop statements within function, of course. The credits for trimRegex
go to jQuery.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745177510a4615265.html
评论列表(0条)