Is it possible? No matter how, in Javascript or jQuery.
For example: $.isFunction($.isFunction());
Upd: But how to check method of a jQuery plugin? Sometimes it not ready at the moment of it call and generates error. Example: $.isFunction($().jqGrid.format)
To pass a function to another function, leave the () off:
$.isFunction($.isFunction); // true!
When you write () you are calling the function, and using the result it returns. $.isFunction() with no argument returns false (because undefined isn't a function), so you are saying $.isFunction(false), which is, naturally, also false.
I wouldn't bother using isFunction merely to check for the existence of something, unless you suspect that someone might have assigned a non-function value to it for some reason. For pure existence-checking, use the in operator:
if ('isFunction' in $) { ...
Yes,
jQuery.fn.exists = function(){return jQuery(this).length>0;}
if ($(selector).exists()) {
// code........
}
Related
I was looking through the React source and stumbled across a requirement with var emptyFunction = require('fbjs/lib/emptyFunction');.
I looked at this function and was confused by what it does.
Here is the function
function makeEmptyFunction<T>(arg: T): (...args: Array<any>) => T {
return function() {
return arg;
};
}
const emptyFunction: (...args: Array<any>) => void = function() {};
In the comments, they give the following explanation which I was confused by:
This function accepts and discards inputs; it has no side effects.
This is primarily useful idiomatically for overridable function
endpoints which always need to be callable, since JS lacks a null-call
idiom ala Cocoa
I have never come across null call idiom and was hoping someone could clarify what this means and explain the purpose of this function in less technical language.
Hopefully this question will not get looked down on because it isn't exactly code related. Maybe it belongs somewhere else, if so I'm sorry.
When programming in JavaScript, we can take a function as a parameter to a certain operation. As an example, a function may have a callback which is invoked after some kind of event.
function doIt(callback) {
// some work
callback();
// more work
}
Now if this callback is an optional parameter and it's not provided, we will get Uncaught TypeError: callback is not a function error because callback is undefined. There are two solutions to this issue. The obvious one is checking the callback with an if statement. Another option is set an empty function as the default value of callback if it's not assigned. This approach is very useful and shines if we have multiple places which invoke the callback function. So we don't need to check it for undefined every time before calling it.
function doIt(callback) {
callback = callback || function(){};
// some work
callback();
// more work
}
Likewise, there are lots of use cases where we can have overridable functions variables. It's a common pattern to set these type of variables to empty function as the default value so that we can call them without worrying about whether those are assigned/overridden or not.
Also, in some special cases, it's useful to have functions which do nothing but return a particular value. makeEmptyFunction is used for creating such functions. Basically, it returns a function which does nothing but returns what ever the parameter pass to it.
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
As you can see in the file, above code generate an empty function which returns false value.
"null call idiom" is something we find in Objective-C/Cocoa programming. It basically allows you to call a method of an uninitialized object (null pointer) without giving any errors like in most of the other languages. I think that's what the author have tried to explain in the comment.
Since JavaScript doesn't have such language feature, we explicitly achieve it using empty functions. Some people call it no-op or noop and you can find similar helpers in other popular JavaScript libraries such as JQuery and AngularJS also.
I'm writing code that needs to reference this inside a prototype, but it cannot be a function. Javascript won't let me do this, but it seems like the length property of arrays and strings does this. I know that length is built-in, and my code is not, but if I can, how do I implement this?
I tried:
String.prototype.prototypeName = (function(aThing){
//Do whatever I need to do here
})(this);
But that references to the global object, because this is called outside of the function.
String.prototype.prototypeName = function(aThing){
//Do whatever I need to do here referencing this
};
However, that is a function, and I can't have that.
I can't have a function because the user can call the function and use typeof on it, and the prototype is supposed to return a string.
For example:
String.prototype.reverse = "Put something that is the reversed string (or this)";
console.log("Stuff"); //"ffutS"
console.log("Anything"); //gnihtynA
You can use a Javascript getter to access a computed property without calling a prototype function. Note this is IE9+ only.
This doesn't work:
var s = '^foo';
console.log(['boot', 'foot'].some(s.match));
Uncaught TypeError: String.prototype.match called on null or undefined
But this does:
var s = '^foo';
console.log(['boot', 'foot'].some(function(i) { return i.match(s) }));
Why is this? I imagine somehow the String.prototype.match function is too "primitive" or something, but why exactly? Since I'm not using ES2015, the second version seems quite verbose. Is there an alternative?
EDIT
When I wrote the above, I actually got it backwards compared to my actual need, which was matching one string against a number of regexes. But thanks to the great answers and comments below, I get it: [/^foo/, /^boo/].some(''.match, 'boot').
Note: The value of this is determined by how the function is called! (exception: bound and arrow functions)
If you pass s.match to .some, then the function will be called with this set to the global object (e.g. window) not the string it "belongs" to.
I.e. it would be equivalent to this:
String.prototype.match.call(window, 'foo')
This cannot work because this has to refer to a string object.
You could solve this by binding the function to a specific this value:
['boot', 'foot'].some(s.match.bind(s));
Learn more about this:
MDN - this
You Don't Know JS: this or That?
How to access the correct `this` context inside a callback?
A function value in Javascript does not bring its object along with it. The value of s.match is a plain function value, with no knowledge that you happened to find it attached to s. In fact, no matter what String you access it through, it's always the same function value:
"foo".match === "bar".match
//= true
When you call a function through an object, Javascript sets this to that object for the duration of the function call. But as soon as anything comes between retrieving the function value and calling it, any object association is lost.
You can create a function that does remember a specific this value using bind, as in #Felix King's answer. someFunction.bind(someObject) has approximately the same meaning as function(arg1, arg2,...) { return someObject.someFunction(arg1, arg2,...); }, but it automatically handles the number of parameters properly.
I have a potentially strange question about this and jQuery plugins
As I understand it, the following is a very basic jQuery plugin:
$.fn.clickclone = function(param){
return this.click(function(){
param.apply(this);
});
};
(pretending that's a plugin that somehow extends click().)
So, if I pass a function as an argument, it does what it needs to do and properly accesses this as a DOM node. Easy.
That's all clear to me.
What's not clear is, is there any way I could pass a non-function argument to the plugin and have it properly access this from the arguments? ie, could I configure the plugin to do something like this:
$("#foo").pluginname(["foo", $(this).text() ]);
Such that for:
Bar
It would properly pass an array to the plugin, with the second item in the array returning the value Bar?
I'm doing this, basically, to provide syntactic sugar for my plugin, where you can pass an array as a shortcut (in addition to using a normal callback function as the main functionality). Except, doing that, I lose access to use of this. Hence my dilemma.
EDIT: This is evil, but, it seems like one work around is to pass the argument as a string and then eval it. Not a workable solution for me, but, it illustrates what I'd like to be able to do:
$.fn.clickclone = function(param){
return this.click(function(){
if(typeof param === "function"){
param.apply(this);
}
else if(typeof param[1] === "string"){
console.dir("This is evil: " + eval(param[1]));
}
});
};
There's no general way to do this without a function, since, in the purely mathematical sense, you are asking for a function of the input (that is, a function of this): something that depends on this in a certain way.
You could perhaps hack it with strings, like so, but you lose the flexibility of functions:
$.fn.alertMe = function (methodToAlert) {
alert(this[methodToAlert]());
};
// usage:
$("#foo").alertMe("text");
$("#foo").alertMe("width");
And if you find using a function acceptable but the this syntax confusing, you can simply do the following:
$.fn.alertMe = function (alertGetter) {
alert(alertGetter($(this));
};
// usage:
$("#foo").alertMe(function (x$) { return x$.text(); });
$("#foo").alertMe(function (x$) { return x$.width(); });
And for completeness I guess I should mention you could probably get away with an eval-based solution, looking something like $("#foo").alertMe("$(this).text()"), but eval is evil and I will neither write up nor condone such a solution. EDIT: oh, I see you have done so in an edit to your original post. Good job corrupting future generations ;)
I am trying to understand how to "chain" JavaScript events together like jQuery does. I found a question here on S.O. that was similar to my goal, but I do not understand the code in the answer.
Code Source
(function( window, undefined ) {
...etc...
}(window)
What does that mean? What is it doing? It reminds me of Jquery's $(document).ready(){} function, but I don't know why this person wrapped his code in this anonymous function that passes window and undefined.
My ultimate goal is to figure out how to execute methods on an object by chaining methods together like jQuery. I know that jQuery already does this but I am looking into this primarily for growth as a developer.
It defines a function (using a function operator as opposed to a function statement). The parenthesis around it ensure that it is treated as the operator rather than the statement.
It then executes it immediately, passing window as an argument.
Essentially, this is the same as:
var myFunction = function( window, undefined ) {
...etc...
};
myFunction(window);
… but without the interstitial variable.
This has nothing to do with jQuery style function chaining, where each method effectively ends with return this (so calling a method on the return value of another method is the same as calling it on the original object).
When a function is called with fewer arguments than its signature contains, the trailing arguments are assigned the value undefined.
So the above is a roundabout way of getting hold of the undefined value even if some lunatic has redefined it by saying var undefined= 'hello';. (This is illegal anyway in ECMAScript Fifth Edition's ‘strict mode’, but JavaScript coders do some weird things sometimes.)
There isn't really a good reason for passing in window like this though... the traditional way to get window if you can't rely on window is to call a function directly and use this.
Either way, this is simply defensive coding against pathological author JavaScript. It's not something you should worry about whilst writing your own code (in any case there's no way you can stop every way someone might mess up their JS environment), and it's nothing to do with chaining.