代码之家  ›  专栏  ›  技术社区  ›  inf3rno

无法添加object.assign到google工作表

  •  0
  • inf3rno  · 技术社区  · 7 年前

    我在google sheets的utils.gs文件中添加了类似的内容:

    Object.assign = function (target, source){
      if (!target || !source)
        throw new Error("Invalid arguments.");
      for (var property in source)
        if (source.hasOwnProperty(property))
          target[property] = source[property];
    };
    

    在同一个脚本文件中,我定义了一个函数,该函数依赖于 Object.assign ,但我总是收到一条错误消息:

    类型错误:在对象函数object()中找不到函数assign{ [object.object的本机代码,arity=1]。

    知道我为什么不能添加吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   inf3rno    7 年前

    这是模块系统中的某种错误。

    此代码有效:

    Mig.GS

    Object.assign = function (target, source){
      if (!target || !source)
        throw new Error("Invalid arguments.");
      for (var property in source)
        if (source.hasOwnProperty(property))
          target[property] = source[property];
      return target;
    };
    
    Logger.log(Object.assign({}, {a:1}));
    
    function main(){
      Logger.log(Object.assign({}, {a:1}));
    }
    

    但如果我移动 Object.assign 到单独的文件:

    Mig.GS

    Logger.log(Object.assign({}, {a:1}));
    
    function main(){
      Logger.log(Object.assign({}, {a:1}));
    }
    

    赋值

    Object.assign = function (target, source){
      if (!target || !source)
        throw new Error("Invalid arguments.");
      for (var property in source)
        if (source.hasOwnProperty(property))
          target[property] = source[property];
      return target;
    };
    

    然后只有第二个 Object.assign() 工程,在 main() 功能。如果我定义和调用 assign() 相反,两种方法都有效。

    请注意,这通常不是问题,因为您通常不会将这两行都添加到 main.gs . 如果使用实用程序函数帮助创建原型,那么最好将每个构造函数和原型定义移动到单独的文件中,而不是在 Mig.GS . 这样你就不会有这样的问题,你可以使用 对象分配 即使在其他实用程序函数和定义中。