Reputation: 2188
I have an idea of making a web-form that receives an object name and outputs all its properties. To do that I wrote a following piece of code:
var html5form = document.getElementsByClassName("html5_form");
html5form[0].onsubmit = function (e) {
var val = e.target.querySelector("input[name=obj]").value,
obj = window[val],
enumObj = new obj();
for (prop in enumObj) {
console.log(prop);
}
return false;
}
I made a datalist with object constructors and attached it to the input field. But I am actually iterating object instances, not constructors. The above mentioned code only works when I enter constructors like DataView and ArrayBuffer and doesn't work on Array, Number and so on. What's wrong with my code? I've tried to debug, but no results.
Upvotes: 0
Views: 1998
Reputation: 50231
JavaScript doesn't have objects for scalars/primitives the way you are thinking. There is boxing, but that is about it.
Boxing of, say, a string primitive to a String Object occurs automatically when you use a method on it, such as 'text'.method()
or (6).toString()
. However, I know of no way to automatically return a boxed value without examining the data type and then choosing the correct conversion yourself (and I'm not even sure if doing so is best practice). And, if you're going to do that, you may as well just change your function to properly deal with primitives as well.
Plus, what would it get you? Let's say you get a String object. What properties are you expecting to enumerate on it? The only property I know of for such things isn't a property, but within a method on the boxed object's prototype, you can use the this
reference--which returns the scalar value.
The problem is that you are expecting objects like Number
or String
to have properties and act like other objects, but they don't and aren't.
Upvotes: 1
Reputation: 21830
Not sure if this is what you're trying to do
window.myObject = function(){};
var objectName = 'myObject';
var objectInstance = new window[objectName];
objectInstance
now contains an instance of myObject
On the other hand if your object is simply an object literal you should not use the new
keyword.
window.myObject = {};
var objectName = 'myObject';
var objectReference = window[objectName];
Upvotes: 0