Uncaught TypeError:使用变量创建对象时,undefined不是函数

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

本文关键字:undefined 函数 创建对象 TypeError 变量 Uncaught      更新时间:2023-09-26

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

var object='fabric.Circle',
     objects={};                         
objects['test1'] = new window[object](); 

它在第三行中给出了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))();