Object methods, "this" Flashcards
let user = {
name: “John”,
age: 30
};
// write a function expression that outputs the below
user.sayHi(); // Hello!
user.sayHi = function() {
alert(“Hello!”);
};
A function that is a property of an object is called its _____.
method
let user = {
};
function sayHi() {
alert(“Hello!”);
}
// add the function as a method to return the below
user.sayHi(); // Hello!
user.sayHi = sayHi;
Write the below as a shorthanded
user = {
sayHi: function() {
alert(“Hello”);
}
};
user = {
sayHi() {
alert(“Hello”);
}
};
let user = {
name: “John”,
age: 30,
sayHi() {
alert( user.name );
}
};
let admin = user;
user = null;
admin.sayHi(); // returns and why?
TypeError: Cannot read property ‘name’ of null
If we decide to copy user to another variable, e.g. admin = user and overwrite user with something else, then it will access the wrong object.
function sayHi() {
alert(this);
}
sayHi(); // returns?
undefined
let user = { name: “John” };
let admin = { name: “Admin” };
function sayHi() {
alert( this.name );
}
user.f = sayHi;
admin.f = sayHi;
user.f(); //
admin.f(); //
John (this == user)
Admin (this == admin)
Arrow functions have no ______
this
function makeUser() {
return {
name: “John”,
ref: this
};
}
let user = makeUser();
alert( user.ref.name ); // returns?
Error: Cannot read property ‘name’ of undefined
function makeUser() {
return {
name: “John”,
ref: this
};
}
let user = makeUser();
alert( user.ref.name );
The above gives an error,
how to correct?
function makeUser() {
return {
name: “John”,
ref() {
return this;
}
};
}
let user = makeUser();
alert( user.ref().name ); // John