覆盖 .toString() 并作为对象返回
在 JavaScript 中可能吗?
像这样的东西:
Response.Cookies =
function() {
return document.cookie;
};
Response.Cookies.toString =
function() {
Cookies = {};
this().replace(/([^=]+)=([^;]+);?/g,
function(foo, label, value) {
return Cookies[label] = value;
});
return Cookies;
};
alert(Response.Cookies); // "does not work"
is it possible in JavaScript?
Something like:
Response.Cookies =
function() {
return document.cookie;
};
Response.Cookies.toString =
function() {
Cookies = {};
this().replace(/([^=]+)=([^;]+);?/g,
function(foo, label, value) {
return Cookies[label] = value;
});
return Cookies;
};
alert(Response.Cookies); // "does not work"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是我认为你想要的:
小提琴:http://jsfiddle.net/ maniator/Yb8NK/
更新:
这是一个没有调用 Response.Cookie() 的版本:http://jsfiddle.net/maniator/Yb8NK/25/
更新#2:
更好的版本:
小提琴:http://jsfiddle.net/maniator/Yb8NK/29/
This is what i think you want:
Fiddle: http://jsfiddle.net/maniator/Yb8NK/
UPDATE:
This is a version without ever calling the
Response.Cookie()
: http://jsfiddle.net/maniator/Yb8NK/25/UPDATE #2:
Even better version:
Fiddle: http://jsfiddle.net/maniator/Yb8NK/29/
不,
toString()
需要返回一个字符串,否则对象到字符串的隐式转换(因为它由alert()
执行)就会失败。你想达到什么目的?No,
toString()
needs to return a string, otherwise the implicit conversion of objects to strings (as it is being performed byalert()
) simply fails. What are you trying to achieve?尝试调用 Response.Cookies,而不仅仅是引用它:
Try invoking
Response.Cookies
, rather than just referencing it: