So..
I am passing data to a function that handles strings and numbers differently.
I would LIKE to be able to pass an array of values and detect what the types of each value is.
row[0] = 23;
row[1] = "this is a string... look at it be a string!";
row[2] = true;
$.each(row, function(){
alert(typeof(this));
//alerts object
});
Is it possible to detect the "actual" datatypes in a given row?
Try
var row = [ 23, "this is a string", true ];
$.each(row, function (index,item) {
alert(typeof(item));
});
// Alerts "number", "string", "boolean"
Whenever possible I try to avoid using "this" in callbacks and using explicit arguments is usually clearer and more predictable.
#Rich suggested the best possible solution - use values passed to callback as arguments. Quote from jQuery doc:
The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.
this.valueOf() might help you to "go back" to primitive value. But still - in that specific example it's better to use values passed as function arguments.
Related
I have a function:
function hello(param){ console.log('param is '+param); }
And two calls. First:
hello(123)
Second:
var a=123; hello(a);
Is there any possible way to tell, from within the hello function, whether param was passed as a var or as a literal value?
NOTICE: I am not trying to solve a problem by this. There are many workarounds of course, I merely wanted to create a nice looking logging function. And also wanted to learn the boundaries of JavaScript. I had this idea, because in JavaScript we have strange and unexpected features, like the ability to obtain function parameter names by calling: function.toString and parsing the text that is returned.
No, primitives like numbers are passed by value in Javascript. The value is copied over for the function, and has no ties to the original.
Edit: How about using an object wrapper to achieve something like this? I'm not sure what you are trying to do exactly.
You could define an array containing objects that you want to keep track of, and check if its in there:
var registry = [] // empty registry
function declareThing(thing){
var arg = { value: thing } // wrap parameter in an object
registry.push(arg) // register object
return arg; //return obj
}
function isRegistered(thingObj){
return (registry.indexOf(thingObj) > -1)
}
var a = declareThing(123);
hello(a);
function hello(param){
console.log(isRegistered(param));
}
One thing I don't understand is why sometimes you put variables inside of ( ) and sometimes you put them before a keyword with a period. Is there a rule on this? Does it have a name? How do I know and how do I remember? This is causing some confusion for me. Example below:
var myNumber1 = 1234;
var myNumber2 = myNumber.toString(); //variable is before keyword with a period
var myNumber1 = "1234";
var myNumber2 = Number(myNumber); //variable is after keyword and inside of parenthesis
Those are two different synatxes.
The first one calls a method of myNumber - a function (toString()) that is run on the object.
The second one calls a function (Number) with myNumber as a parameter - that goes in the parentheses.
To learn more about function and method calls, i recommend reading some tutorials. ;) Here's one by MDN. It's somewhat advanced, but pretty good.
Case 1
Number(myNumber);
In short this is just a function, and you are passing in a variable. from the way you asked your question it seems like you understand how this works.
Case 2
myNumber.toString();
In case 2 you are not actually passing in a variable, you are calling a method of that object.
Dot notation is one of the two ways you can call methods.
[ object ] . [method of that object]
In javascript almost everything is an object, because of this (like it or not) you inherit the methods of Number.prototype in all your numbers.
You can think of .toString() as a method of all number "objects".
If you are interested in learning more about this or how to add more methods your self give THIS a read.
myNumber.toString();
converts myNumber to a "string of characters". Like "abcd". Is not a number.
As every string is between "",
"1234" is a string, not a number.
So
var myNumber2 = Number(myNumber);
converts that string to the number 1234 . "Number" is a function to convert that what you passed trought parenthesis into a number.
I am wondering if I can modify the parameter in the function?
Objects and arrays are passed by reference and changes to the argument you pass to a function will affect the original. All other types behave like they are passed by value and you cannot change the original.
Javascript does this automatically - you cannot specify that something be passed by value or by reference like you can in some other languages. If you want something passed by reference, put it in an array or object and pass the array/object.
Example 1 (passing an object):
function myFunc(myObject) {
// this changes the original object
myObject.ready = true;
}
var obj = {ready: false;};
myFunc(obj);
// obj.ready == true - value is changed
Example 2 (passing a string):
function hello(str) {
str = str + " and goodbye";
alert(str);
}
var greeting = "Hello";
hello(greeting);
// greeting == "Hello" - value is unchanged
Example 3 (passing a string in an object):
function hello(obj) {
obj.str = obj.str + " and goodbye";
alert(obj.str);
}
var o = {greeting: "Hello"};
hello(o);
// o.greeting == "Hello and goodbye" - value is changed
Example 4 (passing a number):
function hello(num) {
num++;
alert(num);
}
var mynum = 5;
hello(mynum);
// mynum == 5 - value is unchanged
Note: One thing that is sometimes confusing is that strings are actually passed by reference (without making a copy), but strings in javascript are immutable (you can't change a string in place in javascript) so if you attempt to modify the string passed as an argument, the changed value ends up in a new string, thus the original string is not changed.
I think you are meaning to ask "Is it possible to change a value passed parameter to a referenced one?"
Javascript is, by nature, a pass by reference language for objects. Primitives like numbers, booleans, and strings are passed by value. If your thinking about how PhP (or a few others) can change the pass by reference or value modifier (IE function passByRef( &refVar ) ) this is not possible with javascript. There is a good post here about how sometimes javascript can be a little more indifferent while passing certain objects and what you might expect, vs what actually happens if it helps.
Is JavaScript a pass-by-reference or pass-by-value language?
In ColdFusion, if you want to reference
<cfargument name="x">
then you say:
arguments.x
In JavaScript, if you have a function:
var myFunction = function(x) {
then, is there a way to explicitly reference the arguments scope like maybe:
arguments[0].x
or something so that you're scoping everything.
There is no way to achieve the same functionality by using the arguments variable, as it holds no information on parameter names. To circumvent this, you could switch from using multiple parameters to one compound parameter object that holds actual parameter values in its members.
<script>
function abc(params) {
var x = params.x;
var y = params["y"];
}
abc( { x: 10, y: "hello" });
</script>
This way however you lose some of the readability of the code at the function signature, plus you must provide param names on the calling side.
You can reference the arguments pseudo-variable, but the arguments are indexed by number, not by name. It's a good idea to avoid messing with arguments directly; a common idiom is to convert it to a real array:
var args = Array.slice.call(arguments, 0);
I'm afraid not. You can explicitly use x or arguments[0] but nothing more. Unless, as pointed out from others, you pass an object.
Because jQuery is a widely used and mature collaborative effort, I can't help but to look at its source for guidance in writing better Javascript. I use the jQuery library all the time along with my PHP applications, but when I look under the hood of this rather sophisticated library I realize just how much I still don't understand about Javascript. Lo, I have a few questions for the SO community. First of all, consider the following code...
$('#element').attr('alt', 'Ivan is SUPER hungry! lolz');
vs
$('#element').attr({'alt': 'Ivan is an ugly monster! omfgz'});
Now, is this to say that the attr() method was designed to accept EITHER an attribute name, an attribute name and a value, or a pair-value map? Can someone give me a short explanation of what a map actually is and the important ways that it differs from an array in Javascript?
Moving on, the whole library is wrapped in this business...
(function(window, undefined) { /* jQuery */ })(window);
I get that the wrapped parentheses cause a behavior similar to body onLoad="function();", but what is this practice called and is it any different than using the onLoad event handler? Also, I can't make heads or tails of the (window) bit there at the end. What exactly is happening with the window object here?
Am I wrong in the assessment that objects are no different than functions in Javascript? Please correct me if I'm wrong on this but $() is the all encompassing jQuery object, but it looks just like a method. Here's another quick question with a code example...
$('#element').attr('alt', 'Adopt a Phantom Cougar from Your Local ASPCA');
... Should look something like this on the inside (maybe I'm wrong about this)...
function $(var element = null) {
if (element != null) {
function attr(var attribute = null, var value = null) {
/* stuff that does things */
}
}
}
Is this the standing procedure for defining objects and their child methods and properties in Javascript? Comparing Javascript to PHP, do you use a period . the same way you would use -> to retrieve a method from an object?
I apologize for this being a bit lengthy, but answers to these questions will reveal a great deal to me about jQuery and Javascript in general. Thanks!
1. Method overloading
$('#element').attr('alt', 'Ivan is SUPER hungry! lolz');
vs
$('#element').attr({'alt': 'Ivan is an ugly monster! omfgz'});
var attr = function (key, value) {
// is first argument an object / map ?
if (typeof key === "object") {
// for each key value pair
for (var k in key) {
// recursively call it.
attr(k, key[k]);
}
} else {
// do magic with key and value
}
}
2. Closures
(function(window, undefined) { /* jQuery */ })(window);
Is not used as an onload handler. It's simply creating new scope inside a function.
This means that var foo is a local variable rather then a global one. It's also creating a real undefined variable to use since Parameters that are not specified passes in undefined
This gaurds againts window.undefined = true which is valid / allowed.
the (window) bit there at the end. What exactly is happening with the window object here?
It's micro optimising window access by making it local. Local variable access is about 0.01% faster then global variable access
Am I wrong in the assessment that objects are no different than functions in Javascript?
Yes and no. All functions are objects. $() just returns a new jQuery object because internally it calls return new jQuery.fn.init();
3. Your snippet
function $(var element = null) {
Javascript does not support default parameter values or optional parameters. Standard practice to emulate this is as follows
function f(o) {
o != null || (o = "default");
}
Comparing Javascript to PHP, do you use a period . the same way you would use -> to retrieve a method from an object?
You can access properties on an object using foo.property or foo["property"] a property can be any type including functions / methods.
4. Miscellanous Questions hidden in your question
Can someone give me a short explanation of what a map actually is and the important ways that it differs from an array in Javascript?
An array is created using var a = [] it simply contains a list of key value pairs where all the keys are positive numbers. It also has all the Array methods. Arrays are also objects.
A map is just an object. An object is simply a bag of key value pairs. You assign some data under a key on the object. This data can be of any type.
For attr, if you give an object instead of a key value pair it will loop on each property.
Look for attr: in jQuery's code, then you'll see it use access. Then look for access: and you will see there is a check on the type of key if it is an object, start a loop.
The wrapping in a function, is to prevent all the code inside to be accessed from outside, and cause unwanted problems. The only parameters that are passed are window that allow to set globals and access the DOM. The undefined I guess it is to make the check on this special value quicker.
I read sometimes jQuery but I didn't start with it, may be you should get some good books to make you an idea first of what some advanced features Javascript has, and then apply your knowledge to the specifics of jQuery.
1 - Yes attr can accept a attribute name for getting a value, a name and a value for setting one value or a map of attribute names and values for settings more than one attribute
2 - A map is basically a JavaScript object e.g:
var map = {
'key1' : 'value1',
'key2' : 'value2'
};
3 - (function(window, undefined) { /* jQuery */ })(window); is something called an anonymous function as it doesn't have a name. In this case it also executes straight away.
A simple example would be:
function test(){
...
}
test();
//As an anonymous function it would be:
(function(){
...
}();
//And it you wanted to pass variables:
function test(abc){
...
}
test(abc);
//As an anonymous function it would be:
(function(abc){
...
}(abc);
this would make it different to the load event, as it is a function not an event.
4 - window is passed as a variable, as it is used internally within jQuery
5 - Objects and functions the same, as everything in JavaScript is an object. jQuery does something like this:
var obj = {
"init" : function(){
}
}
6 - Yes you can use . to retrieve a value on an object but you can also use [] e.g:
var map = {
"test" : 1
}
map.test //1
map["test"] //1
I hope this answers your many questions, let me know if I've missed anything out.
jQuery 1.6.1
The test is typeof key === "object"
if that is true, then you passed a { .... }
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},