These are the ways of creating javascript objects:
function apple(optional_params) {
this.type = "macintosh";
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
}
var apple = {
type: "macintosh",
color: "red",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
}
I really prefer the latter one most since it’s Json syntax, but I’ve seen more of the first one than the latter one.
- Are there any differences between them functionally?
- Could each of them be extended, inherited and cloned/copied?
- In the latter one I could easily create nested elements, is this possible with the first one?
- In the latter one I can’t pass optional parameters?
- Are they serving different purposes? If yes, could you give scenarios where I would use either of them.
This is the way I create Javascript objects in most cases: