Reputation: 5945
I am building functions to help with urls:
var ap = { /* lots of things removed */ }
ap.url = function(base) {
this.base = base
this.data = "cb_=" + parseInt(Math.random()*99999999);
}
ap.url.prototype = {
nv: function (n,v) {this.data=this.data+"&"+ n+"="+encodeURIComponent(v)},
get: function () { return this.base + "?" + this.data; }
};
var u = new ap.url("site.com");
u.nv("p1", "123");
u.nv("p2", "456");
alert( u.get() )
And this appears to work ok.
Is it possible to create a prototype for the object itself? Like:
alert( u() )
I would like u() to do the same thing as u.get()
Upvotes: 0
Views: 84
Reputation: 413996
No, because "u" is not a Function instance. You can however give your "ap.url" prototype a "toString()" and/or "valueOf()" functions to provide string and number representations. Those are used implicitly in various circumstances. Then you can (for example) use a reference to one of those objects in a string concatenation expression, and the runtime will implicitly call your "toString" function.
function C(v) {
this.internal = v;
}
C.prototype = {
toString: function() { return this.internal; }
};
var c = new C("hello world");
alert("The value is: " + c);
Upvotes: 2