繁体   English   中英

未捕获的TypeError:使用变量创建对象时,undefined不是函数

[英]Uncaught TypeError: undefined is not a function while creating the object using variable

我试图通过以下方式创建Fabric.js对象但由于某种原因我被卡住了。

var object='fabric.Circle',
     objects={};                         

objects['test1'] = new window[object](); 

它将第3行中的错误作为Uncaught TypeError: undefined is not a function可以在控制台中检查相同Uncaught TypeError: undefined is not a function

jsfiddle中的示例

你没有按预期获得对象。 您的代码在窗口对象上查找名称为fabric.Circle的属性,而不是您想要window.fabric对象的Circle属性。 您可以使用以下代码执行此操作:

var object='fabric.Circle',
     objects={};                        

 objects['test1']=new getObj(object)(); 


function getObj(path) {
  path = path.split('.');
  var obj = window;
  while (path.length) {
    obj = obj[path.shift()];
  }
  return obj;
}

演示: http//jsbin.com/ABIgoMiR/1/edit

您必须解析object
在这里演示: http//jsfiddle.net/L4WyP/

function getProp(prop) {
    var parts = prop.split('.');
    var obj = window;

    do {
        obj = obj[parts.shift()];
    } while (parts.length);

    return obj;
}

var object = 'fabric.Circle',
    objects = {};

objects['test1'] = new (getProp(object))();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM