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.
There are four ways to create an object in JavaScript - using object literals, using the function constructor, using the Object. create method, and using the class keyword (which is almost the same as using a function constructor).
Creating object with Object. The Object. create() method creates a new object, using an existing object as the prototype of the newly created object.
JavaScript objects have two types of properties: data properties and accessor properties.
The difference is that you can reuse the first one. Example:
function Apple(type, color) {
this.type = type;
this.color = color;
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
}
}
var red = new Apple("Macintosh", "red");
var green = new Apple("Granny Smith", "green");
vs.
var red = {
type: "Macintosh",
color: "red",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
};
var green = {
type: "Granny Smith",
color: "green",
getInfo: function() {
return this.color + ' ' + this.type + ' apple';
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With