Some simple code that I feel should work:
function getUser(id) {
var user;
// get user from DB
return user;
}
var user = getUser(1);
var uname = user.getName();
console.log(uname);
// user is expected to be an instance of the following class:
class User {#
id = 1;#
first = 'Bob';#
last = 'Test'
/*
* # here denotes a private variable. If the syntax is not available,
* simply use an underscore `var _`, so that it becomes
* var _id = 1;
* var _first = 'Bob';
* var _last = 'Test';
* They will no longer be true private variables, but it should be close enough.
*/
constructor() {}
get id() {
return this.#id;
}
set id(value) {
this.#id = value;
}
get firstName() {
return this.#first;
}
set firstName(value) {
this.#first = value;
}
get lastName() {
return this.#last;
}
set lastName(value) {
this.#last = value;
}
getName() {
return `${this.firstName} ${this.lastName}`;
}
}
The error is:
Uncaught TypeError: Cannot read properties of undefined (reading 'getName')
What is going on?
A similar error occurs when I use a service (and fetch
to get the user):
async function getUser(id) {
// get user from API, using fetch from a suitable library (not relevant to question)
let user;
try {
const response = await fetch(`/users/${id}`);
user = await response.json();
} catch {}
return user;
}
(async function () {
const user = await getUser(1);
const uname = user.getName();
console.log(uname);
})();
// user is expected to be an instance of the following class:
class User {
#id = 1;
#first = 'Bob';
#last = 'Test';
/*
* # here denotes a private variable. If the syntax is not available,
* simply use an underscore `var _`, so that it becomes
* var _id = 1;
* var _first = 'Bob';
* var _last = 'Test';
* They will no longer be true private variables, but it should be close enough.
*/
constructor() {}
get id() {
return this.#id;
}
set id(value) {
this.#id = value;
}
get firstName() {
return this.#first;
}
set firstName(value) {
this.#first = value;
}
get lastName() {
return this.#last;
}
set lastName(value) {
this.#last = value;
}
getName() {
return `${this.firstName} ${this.lastName}`;
}
}
You cannot see the error in the Stack Snippet console but must open your Developer Tools to see it there.
The error simply includes a parenthetical "(in promise)" in the error text:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getName')
user
should have agetId()
method? If this is meant to be a canonical Q+A, the question and its assumptions are rather irritating and misleading. I don't see how anyone would be getting anything useful from this.''
in the title to maybe'something'
or'xyz'
. Also, a second code example with a short async section might be good too, for the extremely common case, and yes it's covered by another dup magnet I realize.