www.webdeveloper.com
Results 1 to 2 of 2

Thread: Overriding Date object

  1. #1
    Join Date
    Dec 2005
    Location
    India
    Posts
    490

    Overriding Date object

    Hi all,

    I'm wondering if we can override the Date function in Javascript.
    i.e. var a = new Date();

    Lets say I want to override Date function so that it returns me THIS_IS_A_TEST
    If I do the following, it does override Date
    PHP Code:
    Date=function(e){
        return 
    "THIS_IS_A_TEST";
        }
    Date=function(){
        return 
    "THIS_IS_A_TEST";
        } 
    However, if I do alert(new Date()) doesn't return THIS_IS_A_TEST because it's an object.
    I know that if I just do alert(Date()) THIS_IS_A_TEST will be returned. But I want to imitate the Date functionality keeping aside the other functions of Date.

    Is this possible?

    Thanks,
    Sridhar

  2. #2
    Join Date
    Dec 2003
    Location
    Bucharest, ROMANIA
    Posts
    15,428
    You must work with the prototype of the object. And what you want is, in fact, to add a custom property or a custom method to that object.
    A new property:
    Code:
    Date.prototype.message='THIS_IS_A_TEST';
    var date=new Date();
    alert(date.message);
    A new method:
    Code:
    Date.prototype.alertmessage=function(){alert('THIS_IS_A_TEST')}
    var date=new Date();
    date.alertmessage();
    That technique is known as "extending the prototype of the objects". Use it carefully and try not to modify by mistake a native property/method.

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