Click to See Complete Forum and Search --> : adding methods to objects (and madness)


Dudsmack
10-27-2003, 03:19 PM
I want to add a function to an object. I have a contructor:

function fncName(param1, param2)
{
...some code
}

have an object (with existing properties):
tempObject

I want to add this function to the object so that I could use the object and call it anytime, say:
tempObject.fnc(param1, param2);

so when i try to add it to the object:
tempObject.fnc = new fncName(); it errors because i'm leaving the arguments blank. How can I work it so I can append this function to the object without having to pass it arguments?

Charles
10-27-2003, 03:34 PM
<script type="text/javascript">
<!--
function MyClass (n) {this.n = Number (n)}
MyClass.prototype.toString = function () {return this.n.toString()}
MyClass.prototype.valueOf = function () {return this.n}

o = new MyClass (1);
m = new MyClass (0);
m.toString = function () {return 'My value is ' + this.n.toString()}

alert (o);
alert (m);
// -->
</script>

It is traditional for constructor names to begin with a capitol letter. JavaScript follows the Java Naming Conventions (http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html).