...

View Full Version : changing default constructor



matteo.gazzoni
05-05-2007, 01:00 PM
I have this:


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?

david_kw
05-05-2007, 05:23 PM
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.



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

GJay
05-05-2007, 06:02 PM
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:


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"



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum