Okay, first, your code doesnât work. You canât access your own object from within while defining It, you have to keep in mind that when you call something, that something is read and as in âsayName: "The name of this duck is " + duck.name + "â, how to read a property of an object that wasnât even defined yet?
When you define a function, sayName donât try to call âduck.nameâ to concatenate the values, sayName is just defined as function with instructions that will be read only when you call It.
Iâll try to exemplify for you.
As property:
let duck = { // Detect the keyword âletâ and start to define the variable.
name: âAflacâ, //Property name assigned to value ââAflacââ
numLegs: 2, //Property numLegs assigned to value 2
sayName: "The name of this duck is " + duck.name + â.â //Error. Trying to read undefined âduck.nameâ
};
As function:
let duck = { // Detect the keyword âletâ and start to define the variable.
name: âAflacâ, //Property name assigned to value ââAflacââ
numLegs: 2, //Property numLegs assigned to value 2
sayName: function() {return "The name of this duck is " + duck.name + â.â;} //Property sayName assigned to function() {set of instructions}
};//Finished defining variable.
Also, methods are very important tools in javascript. You can define an unlimited number of instructions inside a function. This is also just an introduction, youâll see a better way to use It in the future.
The duck name one works because there is a variable called duck that youâve defined.
What if you have many duck objects? What if you create the object using some other function, and it doesnât have a name?
let duck = {
name: "Aflac",
numLegs: 2,
sayName: function() {
return "The name of this duck is " + duck.name + ".";
},
};
// I'll create two new objects based
// on duck:
let duck1 = Object.create(duck)
let duck2 = Object.create(duck)
// Then change the name:
duck2.name = "Flappy";
Well, I think you misunderstood his question, he wants to know why he must declare a function. The first code, he did just copy from the exercise and the second one, which is the one that doesnât work is his code.
I understand what they were asking. Itâs this specifically I was replying to, sorry I should have been more clear:
Itâs just an object thatâs been assigned to a variable. If you define a function that refers to that variable within the object, that variable is guaranteed to exist at runtime, so it canât not work. The code is not executed when you define it. If you couldnât do this, it wouldnât be possible to define recursive functions in JavaScript.
Also, functions and objects are different.
It doesnât matter what you put inside them. If you donât call the function, everything will run normally.