The title maybe a little misleading. So don’t confuse things like Arrays
, RegEx
, Boolean
, etc. with Object
! They are all obejcts but a different class. They have common and non-common methods. You can use jQuery's $.type()
method to check any given variable's class.
Most of the time we work with arrays or arrays like jQuery objects. So jQuery has built-in method to check if a variable is an array ($.isArray(var)
).
var bool = true;
var arr = [];
var int = 10;
$.type(bool); // "boolean"
$.type(arr); // "array"
$.type(int); // "number"
Now, back to our initial statement: "Everything is an Object". This means that integers, floats and booleans, etc. also behave like ordinary objects. Which in turn means that we can add and call properties on them as well. Let's see an example:
var bool = true;
var arr = [];
var int = 10;
bool.foo = "bar"; // no syntax error
arr['bar'] = function(){}; // still not an error
int[bool] = "error?"; // nope - not an error
Because everything is an object, JavaScript engine will allow this property assignment methods. However, it will ignore the assignments and when called it will return "undefined". Number
class objects are an exception.
bool.foo; // undefined
arr['bar'] // undefined
int[bool] // undefined
var obj = new Number();
obj.name = "My Name";
console.log(obj["name"]); // "My Name"
So, knowing this little fact helps you understand why for in
loops, for example, allow itirating over arrays. By the way, array keys are internally implemented as object properties. Also, array's .length
property is also not an exception, but a simple property defined on an array object.
var array = [];
array.length; // 0
array[1] = "bar";
array.length; // 2
Since Functions are first class citizens, you can add properties to your functions as well. That's pretty cool.
function myFunk(){
this.name = "My Name";
}
var obj = new myFunk();
obj.newProperty = "Dynamicly Created";
obj.newMethod = function(){ return "Hello"; }
alert( obj["newMethod"]() );
The most important feature is an ability to dynamically created new properties and methods.
TIP:
In case you want your methods to be available to all class instances assign them as a property for.prototype
.
"So every object I tried to use had capabilities of array.".
ReplyDeleteIt is not true. u can access property of an object with the square bracket notation ... but it doesn't mean an object have the same capabilities of an array(and viceversa).
try to iterate object properties.... maybe by index.