let user = {
name: "John",
age: 30,
sayHi() {
alert(this.name);
}
};
user.sayHi(); // John
✔️ Risky way
let user = {
name: "John",
age: 30,
sayHi() {
alert( user.name );
}
};
let admin = user;
user = null;
admin.sayHi(); // Error!
✔️ How to declare a method?
// (*) Better
let user = {
sayHi() {
alert("Hello");
}
};
// (**)
let user = {
sayHi: function() {
alert("Hello");
}
};
let user = { name: "John" };
let admin = { name: "Admin" };
function sayHi() {
alert( this.name ); // no syntax error
}
user.f = sayHi;
admin.f = sayHi;
user.f(); // John
admin.f(); // Admin
let user = {
firstName: "Ilya",
sayHi() {
let arrow = () => alert(this.firstName);
arrow();
}
};
user.sayHi(); // Ilya