/    Sign up×
Community /Pin to ProfileBookmark

Function to get an instance of an object from a string

Hi,

Say I have an object, lets call it myObject, which is an object of the class myClass.

I also have a string, lets call it myString.
myString = “myObject” – a string literal of an object name.

What I want is some type of function, which will take a string, and return an object which has a name the same as the value held in the screen.

So….

[CODE]
myObject = new myClass
myString = “myObject”
anObject = someFunctionIDontKnow(myString)
[/CODE]

anObject should then be a reference to myObject.

Thanks,
Robin

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@CharlesJun 27.2005 — <script type="text/javascript">
<!--
function Foo (s) {this.s = s}

Foo.prototype.toString = function () {return this.s}

foo = new Foo('hello')

alert (window['foo'])
// -->
</script>
Copy linkTweet thisAlerts:
@rmbarnes82authorJun 27.2005 — Thanks! So I take it there's a global array called window maintained by Javascript containing all the scripts varibles?

Robin
Copy linkTweet thisAlerts:
@CharlesJun 27.2005 — Thanks! So I take it there's a global array called window maintained by Javascript containing all the scripts varibles?

Robin[/QUOTE]
Nope. It's just that when you think that you are creating a global variable you are really creating a property of the window object. And all objects can be addressed using the associative array syntax.
×

Success!

Help @rmbarnes82 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...