the question is straight forward. Just like in PHP we have the magic function __construct(), is there any related function or hack I can use in javascript?
Example:
function setLength() {
/* Some work */
}
var a = new Object();
b = new String("Hello");
//Is there anyway the function setLength() will automatically be fired when an Object or String... created?
I’m looking forward to your answers. Thank a lot for any help.
[x]
Trying to overload
Stringwould be a bad idea, especially if working with third party libraries. Same would go for augmentingObject.However, here is how you may do it, but I don’t recommend it..
This obviously won’t be called when creating a primitive string too.
jsFiddle.
You could use a string factory function that returns a new
Stringobject and calls your function.This has some advantages, mainly the
Stringconstructor is not overloaded.