覆盖.toString()并作为对象返回

时间:2011-08-10 19:44:32

标签: javascript override 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"

3 个答案:

答案 0 :(得分:2)

这就是我认为你想要的东西:

var Response = {};

Response.Cookie = 
        function() {
            var self = this;
            Cookies = {};
            this.Cookies = document.cookie;
            this.Cookies = this.Cookies.replace(/([^=]+)=([^;]+);?/g,
                  function(foo, label, value) {
                       Cookies[label] = value;    
                    });
            this.Cookies = Cookies;
        };
Response.Cookie();
for(var cookie in  Response.Cookies){
    alert(cookie + ' = ' +Response.Cookies[cookie])
}

小提琴:http://jsfiddle.net/maniator/Yb8NK/


UPDATE:

这是一个没有调用Response.Cookie()http://jsfiddle.net/maniator/Yb8NK/25/

的版本
var Response = {
    Cookies: null
}
Response.Cookie = (function() {
        var self = Response;
        Cookies = {};
        self.Cookies = document.cookie;
        self.Cookies = self.Cookies.replace(/([^=]+)=([^;]+);?/g, 
            function(foo, label, value) {
                 Cookies[label] = value;
            });
        self.Cookies = Cookies;
    })();
for (var cookie in Response.Cookies) {
    alert(cookie + ' = ' + Response.Cookies[cookie])
}

更新#2:

更好的版本:

var Response = {};
Response.Cookies = (function() {
    var cookies = {};
    var doc_cookies = document.cookie;
    doc_cookies = doc_cookies.replace(/([^=]+)=([^;]+);?/g, 
       function(foo, label, value) {
           cookies[label] = value;
       });
    return cookies;
})();
for (var cookie in Response.Cookies) {
    alert(cookie + ' = ' + Response.Cookies[cookie])
}

小提琴:http://jsfiddle.net/maniator/Yb8NK/29/

答案 1 :(得分:1)

不,toString()需要返回一个字符串,否则将对象隐式转换为字符串(由alert()执行)就会失败。你想要实现什么目标?

答案 2 :(得分:0)

尝试调用Response.Cookies,而不仅仅是引用它:

alert(Response.Cookies());