Why function do not work correctly?

5ccebdafa3d4e112921346.png

Created 2 objects, and function in a global context.

Each object has a property getInfo, with reference to the global function (aka method). Now when you call a method in each object the following must occur. If registered is true, then output the String `date: ` and the value of the data property of this object, otherwise output `Unregistered user ` and the value of the name property of this object.

Important! inside the object can be written only a reference to the function, not the function itself.

I have something does not work, maybe I somehow misunderstood this. Please explain.

Here is the code: https://codepen.io/Izabella4/pen/BeaLxJ?editors=0010
March 20th 20 at 11:51
3 answers
March 20th 20 at 11:53
Solution
When you create the object you just one time perform the function userInfo. Write it without immediate execution, without ()
var userTwo = {
 getInfo: userInfo
};
March 20th 20 at 11:55
Solution

Important! inside the object can be written only a reference to the function, not the function itself.

var userOne = {
 name : "Lera",
 registered : true
 data : "07.12.94",
 getInfo: userInfo // <- a reference to the function
}
console.log(userOne.getInfo()) // <- call method on an object

https://learn.javascript.ru/object-methods
March 20th 20 at 11:57
Solution
function userInfo() {
 if (this.registered === true) {
 return `date: ${this.data}`
 } else {
 return `Unregistered user: ${this.name}`
}
}

var userOne = {
 name : "Lera",
 registered : true
 data : "07.12.94",
 getInfo: userInfo
}

var userTwo = {
 name : "Pasha",
 registered : false,
 data : "05.02.91",
 getInfo: userInfo
}

console.log(userOne.getInfo())


The problem is the function call, and that you perform it on the stage of creation of the object.

Find more questions by tags JavaScript