代码之家  ›  专栏  ›  技术社区  ›  Security Hound

将属性写入cookie

  •  -1
  • Security Hound  · 技术社区  · 16 年前

    我被要求创建一个函数来写入通过函数发送到cookie的“type”属性。我从来没有用过足够多的javascript来理解它,而且这个特殊的请求是非常特殊的,我已经花了8个多小时寻找类似代码的解释。

    如果我声明了以下变量:

    var types = {
        "sugar" : { "color" : "blue", "weight" : 1200, "decoration" : "frosting"},
        "chocolate chip" : { "color" : "brown", "weight" : 12, "chocolateType" : "milk"}
    }; 
    

    以及返回产品重量的以下函数。

    CookieBase.prototype.getWeight = function() { return this.weight; };
    

    我将如何向cookie写入发送给函数的任何类型的属性,因为它实际上是声明的。我能更正一下吗 在getweight函数中,类型是变量吗?

    以下是整个代码片段:

    function CookieBase() {}
    CookieBase.prototype.getWeight = function() { return this.weight; };
    
    var CookieFactory = function(){
        var types = {
            "sugar" : { "color" : "blue", "weight" : 1200, "decoration" : "frosting"},
            "chocolate chip" : { "color" : "brown", "weight" : 12, "chocolateType" : "milk"}
        };
        return {};
    }();
    

    我不是在寻找代码本身,我真的希望有人向我解释这个概念。这是一个工作的筛选过程,所以我想给他们我自己的代码,但我不熟悉这个概念。

    问题是,他们到底想要什么:

    在cookieFactory中,实现一个名为bakecookie的公共方法,该方法采用单个参数--type。此方法应创建一个附加了所请求cookie类型属性的cookie基实例。如果无法创建类型,则返回空值。此代码的长度不应超过大约10行。

    2 回复  |  直到 15 年前
        1
  •  3
  •   outis    16 年前

    要在对象上设置任意属性,可以使用括号语法:

    thing.setProperty = function (type, val) {
        this[type] = val;
    }
    

    还可以使用 for :

    var msg='';
    for (p in thing) {
         msg += p + ': ' + thing[p] + '\n';
    }
    if (console && console.log) {
        console.log(msg);
    } else {
        alert(msg);
    }
    

    结合这些,您可以将一个对象的属性复制到另一个对象。这将使您获得实现 mixins 这听起来像是他们的要求。

        2
  •  2
  •   Community Mohan Dere    9 年前

    通过查看你对答案的最后评论 outis ,听起来您希望实现 烹饪工厂 这样的对象:

    // assuming that the CookieBase constructor is declared
    var CookieFactory = (function () {
      var types = {
        "sugar" : {"color" : "blue", "weight" : 1200, "decoration" : "frosting"},
        "chocolate chip" : {"color" : "brown", "weight" : 12,
                            "chocolateType" : "milk"}
      }; 
    
      return { // public interface
        bakeCookie: function(type){
          var cookie = new CookieBase(),
              cookieType = types[type];
    
          if (!cookieType) return null; // no type found, return null
    
          for(var prop in cookieType) 
            if (cookieType.hasOwnProperty(prop))
              cookie[prop] = cookieType[prop];
    
          return cookie;
        }
      };
    })();
    
    var myCookie = CookieFactory.bakeCookie('sugar');
    // Object color=blue weight=1200 decoration=frosting
    alert(myCookie.getWeight()); // 1200
    

    当你注意到 bakeCookie 方法将创建 CookieBase 对象,它将 复制 传递给它的对象参数的属性。

    因为返回的对象是用 库基 构造函数,您可以访问 CookieBase.prototype 在返回的对象上。