Object methods, "this" Flashcards

1
Q

let user = {
name: “John”,
age: 30
};

// write a function expression that outputs the below

user.sayHi(); // Hello!

A

user.sayHi = function() {
alert(“Hello!”);
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

A function that is a property of an object is called its _____.

A

method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

let user = {
};

function sayHi() {
alert(“Hello!”);
}

// add the function as a method to return the below

user.sayHi(); // Hello!

A

user.sayHi = sayHi;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Write the below as a shorthanded

user = {
sayHi: function() {
alert(“Hello”);
}
};

A

user = {
sayHi() {
alert(“Hello”);
}
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

let user = {
name: “John”,
age: 30,

sayHi() {
alert( user.name );
}

};

let admin = user;
user = null;

admin.sayHi(); // returns and why?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

function sayHi() {
alert(this);
}

sayHi(); // returns?

A

undefined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

let user = { name: “John” };
let admin = { name: “Admin” };

function sayHi() {
alert( this.name );
}

user.f = sayHi;
admin.f = sayHi;

user.f(); //
admin.f(); //

A

John (this == user)
Admin (this == admin)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Arrow functions have no ______

A

this

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

function makeUser() {
return {
name: “John”,
ref: this
};
}

let user = makeUser();

alert( user.ref.name ); // returns?

A

Error: Cannot read property ‘name’ of undefined

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

function makeUser() {
return {
name: “John”,
ref: this
};
}

let user = makeUser();
alert( user.ref.name );

The above gives an error,
how to correct?

A

function makeUser() {
return {
name: “John”,
ref() {
return this;
}
};
}

let user = makeUser();
alert( user.ref().name ); // John

How well did you know this?
1
Not at all
2
3
4
5
Perfectly