Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an image element and its attributes in one go?

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.

like image 209
Þorsteinn Sævar Kristjánsson Avatar asked Dec 20 '22 08:12

Þorsteinn Sævar Kristjánsson


2 Answers

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.

like image 88
Scimonster Avatar answered Mar 07 '23 21:03

Scimonster


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.

like image 25
Felix Kling Avatar answered Mar 07 '23 21:03

Felix Kling