I have a function defined in my JavaScript with two properties: size and url:
function IconInfo() {
this.size = size;
this.url = url;
}
Inside another function I create a new instance of IconInfo and set the properties this way:
function SomeFunction() {
var icon = new IconInfo();
icon.size = 64;
icon.url = "http://somesite.com/image1.png";
}
Isn't there a way to create an instance like the following:
var icon = new IconInfo({
size : 64,
url : "http://somesite.com/image1.png"
});
I like that notation better, it seems more concise and easier to read.
===========================UPDATE================================
Based on Tim's answer of doing it the following way:
var icon = {
size : 64,
url : "http://somesite.com/image1.png"
};
I have the following question.
Let's say I have 2 functions both with the same exact properties and constructor arguments:
function Func1(x) {
this.x = x;
}
function Func2(x) {
this.x = x;
}
And I have a container that holds either type:
function Container() {
this.f = null;
}
If I add one of the functions using that method what type will it actually be?
...
var container = new Container();
container.x = new f { // is f Func1 or Func2?
x: 10;
}
[[Class]]has a different meaning too. So you really mean to ask "how can I distinguish between an instance of Func1 and Func2". Look at the instanceof operator, or perhaps the object's constructor property, but there are issues with both approaches.