从字符串创建对象 [英] Create object from string

查看:235
本文介绍了从字符串创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用字符串创建新对象?
例如,如何将字符串product转换为 var p = new Product

Is it possible to create a new object using a string? For example, how can I convert the string "product" to var p = new Product?

提前致谢。

编辑

我想做的是有一个菜单< a href =#home>< / a>< a href =#products> products< / a> 和每次从href创建相应的对象。

What I want to do is to have a menu with <a href="#home"></a><a href="#products">products</a> and create the corresponding object from the href each time.

推荐答案

如果你知道上下文,是的。假设您在浏览器环境中, Person 是一个全局构造函数。因为任何全局变量都是全局对象的属性,这意味着您可以通过全局对象窗口访问 Person

If you know the context, yes. Let's say you're in a browser environment and Person is a global constructor. Because any global variable is a property of the global object, it means you can access to Person through the global object window:

var p = new Person()

相当于:

var p = new window.Person()

所以你可以使用方括号表示法:

So you can use the square bracket notation:

var p = new window["Person"]();

当然这对每种对象都有效。如果您不想污染全局范围,您可以:

Of course this is valid for every kind of object. If you don't want pollute the global scope, you can have:

var mynamespace = {};

mynamespace.Person = function Person() {..}

var p = new mynamespace["Person"]();

这篇关于从字符串创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆