我正在构建函数来帮助处理 url:
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() )
这似乎工作正常。
是否可以为对象本身创建一个原型(prototype)?喜欢:
alert( u() )
我希望 u() 和 u.get() 做同样的事情
最佳答案
不,因为“u”不是函数实例。但是,您可以为“ap.url”原型(prototype)提供一个“toString()”和/或“valueOf()”函数来提供字符串和数字表示形式。这些在各种情况下隐式使用。然后您可以(例如)在字符串连接表达式中使用对这些对象之一的引用,运行时将隐式调用您的“toString”函数。
function C(v) {
this.internal = v;
}
C.prototype = {
toString: function() { return this.internal; }
};
var c = new C("hello world");
alert("The value is: " + c);
关于对象本身的 Javascript 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14549068/