问题描述:

Here is a sample constructor function that throws "SyntaxError: missing ; before statement Line 3"

function party() {

this.cakes = "Truffle Cake",

this.cookies = "Good Day",

this.drinks: "Wine";

}

While this does not

function party() {

this.cakes = "Truffle Cake",

this.cookies = "Good Day",

this.drinks = "Wine";

}

the difference from first in the second being the use of equals to (=) operator instead of (:) colon operator to assign value drinks property a value. I would like to know the logic why Javascript throws error in the first case.

Also why in the following party.cake etc alerts with "Undefined" as party is an object in itself

function party() {

cake = "Truffle Cake";

cookies = "Good Day";

drinks = "Wine";

}

alert("Cakes in Tonight's Party: " + party.cake);

alert("Cookies in Tonight's Party: " + party.cookies);

alert("Drinks in Tonight's Party: " + party.drinks);

Thanks

网友答案:

The colon is used to separate a property from the value in an object literal. The equals separates the property/variable from a value that is being set.

The error message is correct, you need an equals because you are setting a property. It is not an object literal.

相关阅读:
Top