William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

JavaScript: some tips.

The following are some of my previous collection. They are useful so I put into blog:

  • It is important to note that if you don’t use var to declare a variable, this variable is automatically assigned global scope.
  • It’s recommended that you don’t quote the names of the properties. A property of an object can contain a function, because functions are just data.
    >>> var a = [];
    >>> a[0] = function(what){alert(what);};
    >>> a[0](‘Boo!’);

  • JavaScript uses arrays to represent indexed arrays and objects to represent associative arrays. If you want a hash in JavaScript, you use an object.
    >>> var o = {}; // hash, or associative arrays
    >>> var a = []; // array

  • If your host environment is the web browser, the global object is called window. As an illustration, you can try declaring a global variable, outside of any
    function, such as:
    >>> var a = 1;
    Then you can access this global variable in various ways:
    . As a variable a
    . As a property of the global object, for example window[‘a’] or window.a

  • Object
    Object is the parent of all JavaScript objects, which means that every object you create inherits from it. To create a new empty object you can use the literal notation or the Object() constructor function. The following two lines are equivalent:
    >>> var o = {};
    >>> var o = new Object();

  • An empty object is not completely useless because it already contains some methods and properties. Let’s see a few:
    o.constructor property returns the constructor function
    o.toString() is a method that returns a string representation of the object
    o.valueOf() returns a single-value representation of the object, often this is the object itself

  • toString() will be called internally by JavaScript, when an object is used in a string context. For example alert() works only with strings, so if you call the alert() function passing an object, the method toString() will be called behind the scenes. These two lines will produce the same result:
    >>> alert(o)
    >>> alert(o.toString())

  • valueOf() is another method that all objects provide. For the simple objects (whose constructor is Object()) the valueOf() method will return the object itself.
    >>> o.valueOf() === o
    true
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: