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

EDIT: Question and title changed to reflect my intention in accordance with Felix’s proposal

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 create it, that is, what I'm trying to achieve, is

var imgCollection = {
    catImage: document.createElement("img"),
    catImage: {
        src: "http://whatever.source.com/image.png",
        width: 30,
        height: 30,
    },
}

But the first, in this case catImage: document.createElement("img"), is overwritten.

+4
source share
2 answers

I'm trying to reach ...

This seems to work Object.assign:

var imgCollection = {
    catImage: Object.assign(document.createElement("img"), {
        src: "http://whatever.source.com/image.png",
        width: 30,
        height: 30,
    })
};

Object.assigncopies properties of other arguments to the first argument and returns the first argument. Follow the link for polyfill.

+2
source

String ( ), toString() .

:

var upperMostObject = {};
upperMostObject.obj = new String("topValue"); // as a String object
upperMostObject.obj.subObj = "subValue";

, , String .

String, , (==), (===). typeof someStringObject "object", "string".

( " " ):

var upperMostObject = {
    obj: {
        toString: function(){return "topValue"},
        subObj: "subValue"
    },
}

, , (, upperMostObject.obj == 'topValue'), toString.

+9

All Articles