Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    May 2007
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    changing default constructor

    I have this:

    PHP Code:
    function foo() {
        
    alert'default constructor' ) ;
        
    // methods and properties
    }

    function 
    bar() {
        
    alert'new constructor' ) ;
    }

    foo.prototype.constructor bar ;

    new 
    foo() ; 
    I wanna change the default constructor with new constructor, leaving all foo's methods and properties unchanged, but when create a new instance of foo, still alert 'default constructor'... what's wrong?

  • #2
    Senior Coder
    Join Date
    Nov 2006
    Posts
    1,000
    Thanks
    0
    Thanked 0 Times in 0 Posts
    A constructor is just a function. And a function is just the script data associated with a variable. I believe it is during the "new" portion of the code where the prototype.constructor is created so it would overwrite what you have done at that point. I don't have time to test it but try something like this out.

    Code:
    function foo() { 
        alert( 'default constructor' ) ; 
        // methods and properties 
    } 
    
    function bar() { 
        alert( 'new constructor' ) ; 
        if (needToCallOldFoo) {
            oldFoo();
        }
    } 
    
    var oldFoo = foo;
    var foo = bar; 
    
    new foo() ;
    david_kw

  • #3
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    You might want to take a look at the way the Prototype library allows you to deal with objects and classes, and the extension of them. With prototype you could do:
    Code:
    var  Foo = Class.create();
    Foo.prototype = {
      initialize: function() {
        alert("Foo's constructor");
      },
      bark: function() {
        alert("woof");
      }
    }
    
    var Bar = Class.create();
    Object.extend(Foo.prototype,Bar.prototype);
    Object.extend(Bar.prototype,{
      initialize: function() {
        alert("Bar's constructor");
      }
    });
    
    var a_bar = new Bar(); //alerts "Bar's constructor"
    a_bar.bark(); //alerts "woof"
    My thoughts on some things: http://codemeetsmusic.com
    And my scrapbook of cool things: http://gjones.tumblr.com


  •  

    Posting Permissions

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