0

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()

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Hummm... IE sometimes has a problem figuring out if you're passing the object or if you wanted to call toString(). IE is fine with alert(c) when calling xyz(c) IE wants is passing the object. Chrome can figure it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.