EDIT: Changed the question and title to reflect my intent throughout as per Felix's suggestion
What I want to do is create a subobject "obj" that works as follows:
upperMostObject.obj //This is an image
upperMostObject.obj.src //This is an attribute of the image
and the way I want to be able to create it, that is, what I am trying to achieve is
var imgCollection = {
catImage: document.createElement("img"),
catImage: {
src: "http://whatever.source.com/image.png",
width: 30,
height: 30,
},
}
But the former, in this case catImage: document.createElement("img")
gets overwritten.
You need to either use a String
object (not primitive), or define a custom toString()
method for your object.
The first method:
var upperMostObject = {};
upperMostObject.obj = new String("topValue"); // as a String object
upperMostObject.obj.subObj = "subValue";
This works because a string primitive cannot hold properties, while a String
object can.
Beware when using String
objects that while you can compare using loose equals (==
), you can't with strict equals (===
). Also typeof someStringObject
will be "object"
, not "string"
.
The second method (can be done "in one go"):
var upperMostObject = {
obj: {
toString: function(){return "topValue"},
subObj: "subValue"
},
}
This works because any time you cast the object to a string (eg upperMostObject.obj == 'topValue'
), it will internally call its toString
method.
What I am trying to achieve is ...
This seems like a job for Object.assign
:
var imgCollection = {
catImage: Object.assign(document.createElement("img"), {
src: "http://whatever.source.com/image.png",
width: 30,
height: 30,
})
};
Object.assign
copies the properties of the other arguments to the first argument and returns the first argument. Follow the link for a polyfill.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With