I was wondering how can i pass two different type of value in a single function which accepts single parameter.
let a function is function a(b){return c;}
i'm trying to pass a string while calling the function a some places like a('a string value') then i'll do something with it. Now i need to pass a html element like a(jquery('#someDiv')) and then i'll some another stuff. I need to differentiate both in the function declaration.
Any idea from the experts?
Thanks in advance.
EDIT:
I was looking for a tip to check the data type i'm going to pass as the parameter of the function a. It can be a string or a number or an object or even a function. I don't want to use a fallback. I want to use the last else statement to through an error or exception.
Answer
The typeof operator can be used to test for strings.
if (typeof b == 'string') {
//handle string
}
The second part is a bit more tricky. typeof will return object for a jQuery object. I believe it is safe enough to check if the object's [[Prototype]] is the same as the jQuery constructor's prototype using Object.getPrototypeOf:
else if (Object.getPrototypeOf(b) === $.fn) {
//it is an object that inherits from the jQuery prototype
}
But that isn't supported in IE<9. If a fallback is necessary, instanceof will have a similar effect and can be used instead of Object.getPrototypeOf:
else if (b instanceof jQuery) {}
So a complete solution with old IE support:
if (typeof b == 'string') {
//handle string
} else if (b instanceof jQuery) {
//handle jQuery object
} else {
throw 'Invalid argument';
}
* Note that instanceof will return true even when a constructor "subclasses" jQuery (has a link in the prototype chain to jQuery), while Object.getPrototypeOf will only return true if the object's internal [[Prototype]] points to the same object as the jQuery constructor's prototype. It is rather rare when this will make a difference, but worth keeping in mind.
Nevertheless of these small quirks, this related question has instanceof as the accepted answer, as it is the most compatible solution.
And to explain a couple things, jQuery itself is not a constructor, but its prototype object is shared with jQuery.fn.init which is the actual constructor, and jQuery.fn is a shorthand for jQuery.prototype, so:
jQuery.fn.init.prototype === jQuery.prototype
jQuery.prototype === jQuery.fn
This is going a little off-topic already, so here's a more in-depth article for the interested readers: How jQuery instantiates objects as jQuery.fn.init, and what that means if you want to subclass jQuery
No comments:
Post a Comment