I'm reading a book (I'm new to JavaScript), and I'm just curious if it is possible to create objects using the declaration of object literal notation, but to be able to use the “normal” JavaScript syntax and execute the code in the declaration of this object, let me explain in more detail:
The easiest way to create an object is to use an object literal notation declaration, for example (feel free to correct me if I'm wrong):
var chevy = {
make: "Chevy",
model: "Bel Air",
year: 1957,
color: "red",
passengers: 2,
convertible: false,
mileage: 1021,
started: false,
start: function() {
this.started = true;
}
};
What I don't like about this syntax is: colons sings instead of equal peers, commas instead of semicolons and restrictions: inability to dump code between lines, for example:
var chevy = {
make: "Chevy",
model: "Bel Air",
year: 1957,
color: "red",
passengers: 2,
**invokeFunction()**,
convertible: false,
mileage: 1021,
started: false,
start: function() {
this.started = true;
}
};
At some point, I came across (in the HeadFirst JavaScript book) this brain twister:
(function(food) {
if (food === "cookies") {
alert("More please");
} else if (food === "cake") {
alert("Yum yum");
}
})("cookies");
"cookies". , , "" JavaScript ( ), ( , ):
var chevy = (function() {
var _this = {};
_this.make = "Chevy";
_this.model = "Bel Air";
_this.year = 1957;
_this.color = "red";
_this.passengers = 2;
invokeFunction();
_this.convertible: false;
_this.mileage = 1021;
_this.started = false;
_this.start = function () {
this.started = true;
};
return _this;
})();
. , , - "" , - ( , ):
var chevy = {
function callThisMethodWhenObjectIsCreated() {
this.make = "Chevy";
this.model = "Bel Air";
this.year = 1957;
this.color = "red";
this.passengers = 2;
invokeFunction();
this.convertible = false;
this.mileage = 1021;
this.started = false;
this.start = function () {
this.started = true;
};
}
};
, "" JavaScript . , ?.. , :
var chevy = new (function() {
this.make = "Chevy";
this.model = "Bel Air";
this.year = 1957;
this.color = "red";
this.passengers = 2;
invokeFunction();
this.convertible= false;
this.mileage = 1021;
this.started = false;
this.start = function () {
this.started = true;
};
})();
( ) , {}, (, ), {} JavaScript.
, : - ? - (, ) -, "", , -?