0

I'm trying to get some understanding about new image. Would I be able to create a variable that is supposed to hold an image without assigning a new image object to it? I know you don't have to assign new array when creating an array or new object creating a new object. Is assigning new image to a variable that you are going to hold a image in an old method or do I still need to do it?

0

2 Answers 2

1

There are shorthand examples for new Array() = [] and new Object() = {}, but there is no known shorthand/shortcut for new Image(). That is actually part of the HTML 5 spec, where this code comes from the W3C website:

image = new Image( [ width [, height ] ] )

Returns a new img element, with the width and height attributes set to the values passed in the relevant arguments, if applicable.

See the green box at this link (scroll up slightly): https://www.w3.org/TR/html5/embedded-content-0.html#dom-image

So every JS example on the web seems to be using new Image() in the code examples. However, you can use longhand, like this & assign properties to it.

var img = document.createElement('img');
img.src = '...';
img.height = 123;
img.width = 456;

It's not as cool as "()", because these keyboard pairs are already taken: [], {} and (). Those are for array, object & function parameters, respectively. This looks more like an HTML tag: <>. So there really isn't anything left on the keyboard, which could create a group for a shortcut / shorthand for new Image().

Here are a few JS shorthand links:

  1. http://www.sitepoint.com/shorthand-javascript-techniques/
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators
Sign up to request clarification or add additional context in comments.

Comments

0

@Clomp does a good explanation. But here is another example on how to use this knowledge.

// Create new image element
var image = new Image( 100, 100 );

// Add an image source to element
image.src = 'http://www.publicdomainpictures.net/pictures/130000/velka/blue-tit-bird-clipart.jpg';

// Output new image element to console  
console.log(image);

// Add image element to body
$('body').html(image);

https://jsbin.com/medohiquti/edit?html,js,output

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.