Quantcast
Channel: Joe – STEINBRING.net
Viewing all articles
Browse latest Browse all 100

How to get the source of objects within JavaScript

$
0
0

There is an interesting little method within JavaScript called toSource() that can give you some nice insights into your variables.  The resulting output can differ greatly, depending on the variable that you run it against.  Let’s take a look at a few examples.

In our first example, there is a “person” object.  A person has a fname, lname, and website.  We then create a “joe” object, providing my first name, last name, and website address.  As you can see, it the value of “joe.toSource()” ends up being a JSON representation of the object.

In our second example, there is an “isCool” boolean that is set to true.  I then set the “joe” variable to be equal to “isCool”.  The result of running “toSource()” against “joe” is the true boolean.

Our third example looks at its effect with dates and numbers.  This time, we are looking at two values.  First, we create a new date object called “date” and got its source.  Next, we extracted the month from the date and got its source.  You will notice that the date is indeed a date object but the result of running the “getMonth()” method against it is a number object.

Our fourth and final example shows what happens when you run the method against a string literal.  In it, we just set the name variable to equal “Joe” and the result is indeed a string.

It should be noted that the toSource() method does not work in Internet Explorer or Chrome.  If you want to use it, you will need to do so in Firefox.  For this reason, I would not use this method in production.  It is still interesting, though.


Viewing all articles
Browse latest Browse all 100

Latest Images

Trending Articles





Latest Images