www.webdeveloper.com
Results 1 to 4 of 4

Thread: Javascript: methods can be applied to a non-object variable?

  1. #1
    Join Date
    Jan 2013
    Posts
    84

    Javascript: methods can be applied to a non-object variable?

    Hi, sorry for the noobish question, i'm new in JS and in this forum (and sorry for my english too, i'm italian)


    According to the Javascript The Complete Guide 8th Edition,

    "When we combine functions with objects, we get methods"

    Always according to the book, an object is a collection of name/value pairs, or a string to value map.
    exemple:
    var book = { // Objects are enclosed in curly braces.
    topic: "JavaScript", // The property "topic" has value "JavaScript".
    fat: true // The property "fat" has value true.
    };


    So, for what reason methods can be apllied to the arrays too ?
    For exemple
    myarray.reverse() is one of default method included in the JS API


    I'm little confused about methods so... They can be applied only to the objects AND arrays? Or they can be applied to ANY kind of variable (for exemple, numeric, string, etc..) declared in JS?

  2. #2
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    You can't add methods directly to primitive objects (strings, numbers, booleans, undefined, null) but you can add methods to their prototype (except for undefined and null) which will make those methods available on all objects of that type. Example:

    Code:
    var str = 'asdf';
    str.myMethod = function(){}; // won't work
    
    String.prototype.myMethod = function(){ // we need to do this
        alert('Hello!');
    };
    
    str.myMethod(); // works!
    Note that all things in JavaScript are objects, even functions!
    Last edited by ReFreezed; 01-14-2013 at 02:26 PM.

  3. #3
    Join Date
    Jan 2013
    Posts
    84
    many thanks

  4. #4
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    if the string is read-only in purpose, you can add methods by making a String object using new.
    The same goes for Numbers.

    example:


    Code:
    x=new Number(5);
    x.double=function(){return this*2};
    
    alert(  x.double()  ) // shows 10

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles