JavaScript - The Complete Guide 2022

Section 9: Objects - A Closer Look - Beyond the Basics

olivia_yj 2022. 10. 19. 16:08

The goals

๐Ÿ’ช๐ŸปWhat are Objects

โœŒ๐ŸปObjects in JavaScript

๐Ÿ‘๐ŸปAdding a Method to Objects

 

 

๊ฐ์ฒด & ์›์‹œ ๊ฐ’

๊ฐ์ฒด๋Š” ์ฐธ์กฐ ๊ฐ’์ด๋ผ๋Š” ์ ์€ ์ด๋ฏธ ๋ฐฐ์šฐ์…จ์Šต๋‹ˆ๋‹ค.

์•„์ง ๋ช…ํ™•ํ•˜์ง€ ์•Š์„ ์ˆ˜๋„ ์žˆ์ง€๋งŒ, ๊ฐ์ฒด๊ฐ€ ์›์‹œ ๊ฐ’์œผ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค๋Š” ์ ์„ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค.

๋‹ค์Œ์€ ์˜ˆ์‹œ์ž…๋‹ˆ๋‹ค.

const complexPerson = {
	name: 'Max',
	hobbies: ['Sports', 'Cooking'],
	address: {
		street: 'Some Street 5',
		stateId: 5,
		country: 'Germany',
		phone: {
			number: 12 345 678 9,
			isMobile: true
		}
	},
};

complexPerson ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ค‘์ฒฉ๋œ ์ฐธ์กฐ ๊ฐ’(์ค‘์ฒฉ๋œ ๋ฐฐ์—ด๊ณผ ๊ฐ์ฒด)์ด ์žˆ๊ธด ํ•˜์ง€๋งŒ ์ด ๊ฐ์ฒด๋ฅผ ํŒŒํ—ค์ณ๋ณด๋ฉด ๊ฒฐ๊ตญ ์›์‹œ ๊ฐ’์ด ๋ฉ๋‹ˆ๋‹ค.

name์€ ๋ฌธ์ž์—ด('Max')์„ ์ €์žฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค => ์›์‹œ ๊ฐ’

hobbies ๋Š” ๋ฌธ์ž์—ด๋กœ ๋œ('Sports', 'Cooking') (์ฆ‰ ์ฐธ์กฐ ๊ฐ’) ๋ฐฐ์—ด์„ ์ €์žฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค => ์›์‹œ ๊ฐ’

address ๋Š” 'Some Street 5' ์™€ ๊ฐ™์€ ์›์‹œ ๊ฐ’๊ณผ ์ค‘์ฒฉ๋œ ๊ฐ์ฒด(phone)๋ฅผ ํฌํ•จํ•˜๊ฒŒ ๋˜์ง€๋งŒ phone์„ ๋” ์ž์„ธํžˆ ์‚ดํŽด๋ณด๋ฉด ์ˆซ์ž์™€ ๋ถˆ๋ฆฌ์–ธ๋งŒ ์žˆ์Šต๋‹ˆ๋‹ค => ์›์‹œ ๊ฐ’

๋”ฐ๋ผ์„œ ์›์‹œ ๊ฐ’์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋Š” ํ•ต์‹ฌ ๊ตฌ์„ฑ ์š”์†Œ์ด๊ณ  ๊ฐ์ฒด(์™€ ๋ฐฐ์—ด)๋Š” ํ•ด๋‹น ๋ฐ์ดํ„ฐ๋ฅผ ๊ตฌ์„ฑํ•˜๊ณ  ์ž‘์—…ํ•˜๋Š” ๋ฐ์— ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

 

Add Method to object in JavaScript

 

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects. This chapter describes how to use objects, properties, functions, and methods, and how to create your own objects.

 

Adding a method to the object

Adding a method to a javascript object is easier than adding a method to an object constructor. We need to assign the method to the existing property to ensure task completion.

Example

In the following example, initially, the object type is created and later on, the properties of the object were created. Once the creation of properties is done, a method is assigned to each of the objects and the properties were accessed using the method as our requirement.

 

<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
   }
   var person1 = new Business("Trump", "$28.05billion", "73", "President");
   var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
   person1.det = function() {
      return this.Name + " "+" has a property of net worth "+ "" + this.prop;
   };
   person2.det = function() {
      return this.Name + " "+" has a property of net worth "+ "" + this.prop;
   };
   document.write(person2.det() +" and "+person1.det());
</script>
</body>
</html>

Output

Jackma has a property of net worth $35.6 billion and Trump has a property of net worth $28.05billion

 

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

What is this?

In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any object.

We don't use the arrow function in object method tho!

 

bind()

Function.prototype.bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Parameters

 
thisArg

The value to be passed as the this parameter to the target function func when the bound function is called. If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects. The value is ignored if the bound function is constructed using the new operator.

arg1, …, argN Optional

Arguments to prepend to arguments provided to the bound function when invoking func.

Return value

A copy of the given function with the specified this value, and initial arguments (if provided).

Introduction to JavaScript bind() method

The bind() method returns a new function, when invoked, has its this sets to a specific value.

The following illustrates the syntax of the bind() method:

fn.bind(thisArg[, arg1[, arg2[, ...]]])

In this syntax, the bind() method returns a copy of the function fn with the specific this value (thisArg) and arguments (arg1, arg2, …).

Unlike the call() and apply() methods, the bind() method doesn’t immediately execute the function. It just returns a new version of the function whose this sets to thisArg argument.

Using JavaScript bind() for function binding

When you pass a method an object is to another function as a callback, the this is lost. For example:

let person = { name: 'John Doe', getName: function() { console.log(this.name); } }; setTimeout(person.getName, 1000);

Output:

undefined

As you can see clearly from the output, the person.getName() returns undefined instead of 'John Doe'.

This is because setTimeout() received the function person.getName separately from the person object.

The statement:

setTimeout(person.getName, 1000);

can be rewritten as:

let f = person.getName; setTimeout(f, 1000); // lost person context

The this inside the setTimeout() function is set to the global object in non-strict mode and undefined in the strict mode.

Therefore, when the callback person.getName is invoked, the name does not exist in the global object, it is set to undefined.

To fix the issue, you can wrap the call to the person.getName method in an anonymous function, like this:

setTimeout(function () { person.getName(); }, 1000);

This works because it gets the person from the outer scope and then calls the method getName().

Or you can use the bind() method:

let f = person.getName.bind(person); setTimeout(f, 1000);

In this code:

  • First, bind the person.getName method to the person object.
  • Second, pass the bound function f with this value set to the person object to the setTimeout() function.

Using bind() to borrow methods from a different object

Suppose you have a runner object that has the run() method:

let runner = { 
	name: 'Runner', 
    run: function(speed) { 
    	console.log(this.name + ' runs at ' + speed + ' mph.'); 
      } 
  };

And the flyer object that has the fly() method:

let flyer = { 
	name: 'Flyer', 
    fly: function(speed) { 
    	console.log(this.name + ' flies at ' + speed + ' mph.'); 
      } 
 };

If you want the flyer object to be able to run, you can use the bind() method to create the run() function with the this  sets to the flyer object:

let run = runner.run.bind(flyer, 20); run();

In this statement:

  • Call the bind() method of the runner.run() method and pass in the flyer object as the first argument and 20 as the second argument.
  • Invoke the run() function.

Output:

Flyer runs at 20 mph.

The ability to borrow a method of an object without making a copy of that method and maintain it in two separate places is very powerful in JavaScript.

Summary

  • The bind() method creates a new function, when invoked, has the this sets to a provided value.
  • The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

call()

Introduction to the JavaScript call() method

In JavaScript, a function is an instance of the Function type. For example:

function add(x, y) { 
	return x + y; 
} 
console.log(add instanceof Function); // true

The Function.prototype type has the call() method with the following syntax:

functionName.call(thisArg, arg1, arg2, ...);

In this syntax, the call() method calls a function functionName with the arguments (arg1, arg2, …) and the this set to thisArg object inside the function.

  • The thisArg is the object that the this object references inside the function functionName.
  • The arg1, arg2, .. are the function arguments passed into the functionName.

The call() method returns the result of calling the functionName().

The following example defines the add() function and calls it normally:

function add(x, y) { 
	return x + y; 
} 
let result = add(10, 20); 
console.log(result); // 30

The following calls the add() function but use the call() method instead:

function add(x, y) { 
	return x + y; 
} 
let result = add.call(this, 10, 20); 
console.log(result); // 30

By default, the this inside the function is set to the global object i.e., window in the web browsers and global in Node.js.

Note that in the strict mode, the this inside the function is set to undefined instead of the global object.

Consider the following example:

var greeting = 'Hi'; 
var messenger = { greeting: 'Hello' } 
function say(name) { 
	console.log(this.greeting + ' ' + name); 
}

Inside the say() function, we reference the greeting via the this value. If you just invoke the say() function via the call() method as follows:

say.call(this,'John');

It’ll show the following output to the console:

"Hi John"

However, when you invoke the call() method of say function object and pass the messenger object as the this value:

say.call(messenger,'John');

The output will be:

"Hello John"

In this case, the this value inside the say() function references the messenger object, not the global object.

Using the JavaScript call() method to chain constructors for an object

You can use the call() method for chaining constructors of an object. Consider the following example:

function Box(height, width) { 
	this.height = height; 
    this.width = width; 
} 
function Widget(height, width, color) { 
	Box.call(this, height, width); 
    this.color = color; 
} 
let widget = new Widget('red', 100, 200); 
console.log(widget);

Output:

Widget { height: 'red', width: 100, color: 200 }

In this example:

  • First, initialize the Box object with two properties: height and width.
  • Second, invoke the call() method of the Box object inside the Widget object, set the this value to the Widget object.

Using the JavaScript call() method for function borrowing

The following example illustrates how to use the call() method for borrowing functions:

const car = { 
	name: 'car', 
    start() { 
    	console.log('Start the ' + this.name); 
    }, 
    speedUp() { 
    	console.log('Speed up the ' + this.name); 
    }, 
    stop() { 
    	console.log('Stop the ' + this.name); 
    }, 
}; 
const aircraft = { 
	name: 'aircraft', 
    fly() { 
    	console.log('Fly'); 
    }, 
}; 
car.start.call(aircraft); 
car.speedUp.call(aircraft); 
aircraft.fly();

Output:

Start the aircraft 
Speed up the aircraft 
Fly

How it works.

First, define a car object with one property name and three methods start, speedUp, and stop:

const car = { 
	name: 'car', 
    start() { 
    	console.log('Start the ' + this.name); 
    }, 
    speedUp() { 
    	console.log('Speed up the ' + this.name); 
    }, 
    stop() { 
    	console.log('Stop the ' + this.name); 
    }, 
};

Second, define the aircraft object with one property name and a method:

const aircraft = { 
	name: 'aircraft', 
    fly() { 
    	console.log('Fly'); 
    }, 
};

Third, call the start() and speedUp() method of the car object and the fly() method of the aircraft object. However, passing the aircraft as the first argument into the start() and speedUp() methods:

car.start.call(aircraft); 
car.speedUp.call(aircraft); 
aircraft.fly();

Inside the start() and speedUp() methods, the this references the aircraft object, not the car object. Therefore, the this.name returns the 'aircraf' string. Hence, the methods output the following message:

Start the aircraft 
Speed up the aircraft

Technically, the aircraft object borrows the start() and speedUp() method of the car object. And function borrowing refers to an object that uses a method of another object.

The following example illustrates how the arguments object borrows the filter() method of the Array.prototype via the call() function:

function isOdd(number) { 
	return number % 2; 
} 
function getOddNumbers() { 
	return Array.prototype.filter.call(arguments, isOdd); 
} 
let results = getOddNumbers(10, 1, 3, 4, 8, 9); 
console.log(results);

Output:

[ 1, 3, 9 ]

How it works.

First, define the isOdd() function that returns true if the number is an odd number:

function isOdd(number) { 
	return number % 2; 
}

Second, define the getOddNumbers() function that accepts any number of arguments and returns an array that contains only odd numbers:

function getOddNumbers() { 
	return Array.prototype.filter.call(arguments, isOdd); 
}

In this example, the arguments object borrows the filter() method of the Array.prototype object.

Third, call the getOddNumbers() function:

let results = getOddNumbers(10, 1, 3, 4, 8, 9); 
console.log(results);

In this tutorial, you have learned about the JavaScript call() method and how to use it more effectively.

 

 

apply()

Introduction to the JavaScript apply() method

The Function.prototype.apply() method allows you to call a function with a given this value and arguments provided as an array. Here is the syntax of the apply() method:

fn.apply(thisArg, [args]);

The apply() method accepts two arguments:

  • The thisArg is the value of this provided for the call to the function fn.
  • The args argument is an array that specifies the arguments of the function fn. Since the ES5, the args argument can be an array-like object or array object.

THe apply() method is similar to the call() method except that it takes the arguments of the function as an array instead of the individual arguments.

JavaScript apply() method examples

Let’s take some examples of using the apply() method.

1) Simple JavaScript apply() method example

Suppose that you have a person object:

const person = { firstName: 'John', lastName: 'Doe' }

…and a function named greet() as follows:

function greet(greeting, message) { 
	return `${greeting} ${this.firstName}. ${message}`; 
}

The greet() function accepts two parameters: greeting and message. Inside the greet() function, we reference an object that has the firstName property.

The following example shows how to use the apply() method to call the greet() function with the this set to the person object:

let result = greet.apply(
	person, ['Hello', 'How are you?']
 ); 
 console.log(result);

Output:

Hello John. How are you?

In this example, we set the this value inside the function to the person object. The arguments of the greet() function was passed into the apply() method as an array.

The apply() method invoked the greet() function with the this value set to the person object and arguments as an array ['Hello', 'How are you?'].

If you use the call() method, you need to pass the arguments of the greet() function separately as follows:

let result = greet.call(person, Hello', 'How are you?');

2) Function borrowing

The apply() method allows an object to borrow the method of another object without duplicating the code.

Suppose that you have the following computer object:

const computer = { 
	name: 'MacBook', 
    isOn: false, 
    turnOn() { 
    	this.isOn = true; 
        return `The ${this.name} is On`; 
   }, 
    turnOff() { 
    	this.isOn = false; 
        return `The ${this.name} is Off`; 
   } 
};

… and the following server object:

const server = { name: 'Dell PowerEdge T30', isOn: false };

The server object doesn’t have the turnOn() and turnOff() methods.

To execute the turnOn() method of the computer object on the server object, you can use the apply() method as follows:

let result = computer.turnOn.apply(server); console.log(result);

Output:

The Dell PowerEdge T30 is On

In this example, the server object borrows the turnOn() method of the computer object.

Similarly, you can call the turnOff() method of the computer object on the server object:

let result = computer.turnOff.apply(server); console.log(result);

Output:

The Dell PowerEdge T30 is Off

3) Using the apply() method to append an array to another

The apply() method allows you to append elements of an array to another:

let arr = [1, 2, 3]; 
let numbers = [4, 5, 6]; 
arr.push.apply(arr, numbers); 
console.log(arr);

In this example, the apply() method modifies the original array arr. Note that the Array.prototype.concat() method also provides the same result except that it returns the new array instead of modifying the original array.

Summary

  • The apply() method invokes a function with a given this value and arguments provided as an array.
  • The apply() method is similar to the call() method excepts that it accepts the arguments of the function as an array instead of individual arguments.

 

“This” - ์š”์•ฝ

this ํ‚ค์›Œ๋“œ๋Š” JavaScript์—์„œ ๊ณจ์นซ๊ฑฐ๋ฆฌ๊ฐ€ ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์š”์•ฝ์ด ํ•ด๊ฒฐ์ฑ…์ด ๋˜๊ธฐ๋ฅผ ๋ฐ”๋ž๋‹ˆ๋‹ค.

this๋Š” ์‚ฌ์šฉ ์œ„์น˜์™€ (ํ•จ์ˆ˜์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ฒฝ์šฐ) ํ•จ์ˆ˜ ํ˜ธ์ถœ ๋ฐฉ๋ฒ•์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ๊ฒƒ์„ ์ฐธ์กฐํ•ฉ๋‹ˆ๋‹ค.

๋ณดํ†ต this๋Š” (ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ฒฝ์šฐ) ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•œ '๋ฌด์–ธ๊ฐ€'๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค. ์ด๋Š” ์ „์—ญ ์ปจํ…์ŠคํŠธ, ๊ฐ์ฒด ๋˜๋Š” ๋ฐ”์ธ๋”ฉ๋œ ๋ฐ์ดํ„ฐ/๊ฐ์ฒด์ผ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค(์˜ˆ: ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ํด๋ฆญ ์ด๋ฒคํŠธ๋ฅผ ํŠธ๋ฆฌ๊ฑฐํ•œ ๋ฒ„ํŠผ๊ณผ this๋ฅผ ๋ฐ”์ธ๋“œํ•  ๋•Œ).

1) ์ „์—ญ ์ปจํ…์ŠคํŠธ(์ฆ‰ ํ•จ์ˆ˜ ์™ธ๋ถ€)์—์„œ์˜  this

function something() { ... }
 
console.log(this); // ์ „์—ญ ๊ฐ์ฒด(๋ธŒ๋ผ์šฐ์ €์˜ ์ฐฝ)๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค - ํ•ญ์ƒ(์—„๊ฒฉ ๋ชจ๋“œ์—์„œ๋„)!

2) (ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๊ฐ€ ์•„๋‹Œ)ํ•จ์ˆ˜์—์„œ์˜ this - ์ „์—ญ ์ปจํ…์ŠคํŠธ์—์„œ ํ˜ธ์ถœ๋์„ ๋•Œ

function something() { 
    console.log(this);
}
 
something(); // ์—„๊ฒฉ ๋ชจ๋“œ๊ฐ€ ์•„๋‹ ๋• ์ „์—ญ ๊ฐ์ฒด(๋ธŒ๋ผ์šฐ์ €์˜ ์ฐฝ)๋ฅผ ๊ธฐ๋กํ•˜๊ณ  ์—„๊ฒฉ

3) ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์—์„œ์˜ this - ์ „์—ญ ์ปจํ…์ŠคํŠธ์—์„œ ํ˜ธ์ถœ๋์„ ๋•Œ

const something = () => {
console.log(this);
}
 
something(); // ์ „์—ญ ๊ฐ์ฒด(๋ธŒ๋ผ์šฐ์ €์˜ ์ฐฝ)๋ฅผ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค - ํ•ญ์ƒ(์—„๊ฒฉ ๋ชจ๋“œ์—์„œ๋„)!

4) (ํ™”์‚ดํ‘œ๊ฐ€ ์•„๋‹Œ) ๋ฉ”์„œ๋“œ์—์„œ์˜ this - ๊ฐ์ฒด์—์„œ ํ˜ธ์ถœ๋์„ ๋•Œ

const person = {
name: 'Max',
greet: function() { // or use method shorthand: greet() { ... }
console.log(this.name);
}
};
 
person.greet(); // 'Max'๋ฅผ ๊ธฐ๋กํ•˜๊ณ , "this"๋Š” person ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•จ

5) (ํ™”์‚ดํ‘œ ํ•จ์ˆ˜) ๋ฉ”์„œ๋“œ์—์„œ์˜ this - ๊ฐ์ฒด์—์„œ ํ˜ธ์ถœ๋์„ ๋•Œ

const person = {
name: 'Max',
greet: () => {
console.log(this.name);
}
};
 
person.greet(); // ์•„๋ฌด๊ฒƒ๋„ ๊ธฐ๋กํ•˜์ง€ ์•Š์Œ(์•„๋‹ˆ๋ฉด ์ฐฝ ๊ฐ์ฒด์˜ ์ผ๋ถ€ ์ „์—ญ ์ด๋ฆ„์„ ๊ธฐ๋ก), "this"๋Š” ์—„๊ฒฉ ๋ชจ๋“œ์—์„œ๋„ ์ „์—ญ(์ฐฝ) ๊ฐ์ฒด๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.

this๋Š” ๋‹ค๋ฅธ ๊ฐ์ฒด์—์„œ ํ˜ธ์ถœํ•˜๋Š” ๊ฒฝ์šฐ ์˜ˆ์ƒ์น˜ ๋ชปํ•œ ๊ฒƒ์„ ๋‚˜ํƒ€๋‚ผ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ์‹œ:

const person = {
name: 'Max',
greet() {
console.log(this.name);
}
};
 
const anotherPerson = { name: 'Manuel' }; // ๋‚ด์žฅ๋œ greet ๋ฉ”์„œ๋“œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค!
 
anotherPerson.sayHi = person.greet; // greet์€ ์—ฌ๊ธฐ์„œ ํ˜ธ์ถœ๋˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ "anotherPerson" ๊ฐ์ฒด์˜ ์ƒˆ๋กœ์šด ํ”„๋กœํผํ‹ฐ/๋ฉ”์„œ๋“œ์— ํ• ๋‹น๋ฉ๋‹ˆ๋‹ค.
 
anotherPerson.sayHi(); // "anotherPerson" ๊ฐ์ฒด์—์„œ ํ˜ธ์ถœ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ‘Manuel’์„ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค => "this"๋Š” ํ˜ธ์ถœํ•œ "๋ฌด์–ธ๊ฐ€"๋ฅผ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค

ํ—ท๊ฐˆ๋ฆฌ๋Š” ๊ฒฝ์šฐ์—๋Š” console.log(this);๊ฐ€ ํ•ญ์ƒ this๊ฐ€ ํ˜„์žฌ ๋ฌด์—‡์„ ์˜๋ฏธํ•˜๋Š”์ง€ ์•Œ์•„๋‚ด๋Š” ๋ฐ์— ๋„์›€์„ ์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!

Quiz

์งˆ๋ฌธ 3:

์•„๋ž˜ ์˜ˆ์—์„œ this๊ฐ€ ์ฐธ์กฐํ•˜๋Š” ๊ฒƒ์€ ๋ฌด์—‡์ผ๊นŒ์š”?

const person = {
name: 'Max',
greet() {
console.log(this); // ???
console.log(this.name);
}
};
 
const admin = { age: 30 };
 
admin.greet = person.greet;
admin.greet();

์ •๋‹ต: this ๋Š” admin ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•ฉ๋‹ˆ๋‹ค

 "person"์—์„œ ์ •์˜๋˜์–ด ์žˆ์ง€๋งŒ "admin"์— ์ถ”๊ฐ€๋œ ๋‹ค์Œ "admin"์— ๋Œ€ํ•ด ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ "this"๋Š” admin ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•ฉ๋‹ˆ๋‹ค.

 

Getters and Setters

In this tutorial, you will learn about JavaScript getter and setter methods with the help of examples.

In JavaScript, there are two kinds of object properties:

  • Data properties
  • Accessor properties

Data Property

Here's an example of data property that we have been using in the previous tutorials.

const student = {

    // data property
    firstName: 'Monica';
};

Accessor Property

In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords:

  • get - to define a getter method to get the property value
  • set - to define a setter method to set the property value

JavaScript Getter

In JavaScript, getter methods are used to access the properties of an object. For example,

const student = {

    // data property
    firstName: 'Monica',
    
    // accessor property(getter)
    get getName() {
        return this.firstName;
    }
};

// accessing data property
console.log(student.firstName); // Monica

// accessing getter methods
console.log(student.getName); // Monica

// trying to access as a method
console.log(student.getName()); // error
 

In the above program, a getter method getName() is created to access the property of an object.

get getName() {
    return this.firstName;
}

Note: To create a getter method, the get keyword is used.

And also when accessing the value, we access the value as a property.

student.getName;

When you try to access the value as a method, an error occurs.

console.log(student.getName()); // error

JavaScript Setter

In JavaScript, setter methods are used to change the values of an object. For example,

const student = {
    firstName: 'Monica',
    
    //accessor property(setter)
    set changeName(newName) {
        this.firstName = newName;
    }
};

console.log(student.firstName); // Monica

// change(set) object property using a setter
student.changeName = 'Sarah';

console.log(student.firstName); // Sarah
 
 

In the above example, the setter method is used to change the value of an object.

set changeName(newName) {
    this.firstName = newName;
}

Note: To create a setter method, the set keyword is used.

As shown in the above program, the value of firstName is Monica.

Then the value is changed to Sarah.

student.changeName = 'Sarah';

Note: Setter must have exactly one formal parameter.


JavaScript Object.defineProperty()

In JavaScript, you can also use Object.defineProperty() method to add getters and setters. For example,

const student = {
    firstName: 'Monica'
}

// getting property
Object.defineProperty(student, "getName", {
    get : function () {
        return this.firstName;
    }
});

// setting property
Object.defineProperty(student, "changeName", {
    set : function (value) {
        this.firstName = value;
    }
});

console.log(student.firstName); // Monica

// changing the property value
student.changeName = 'Sarah';

console.log(student.firstName); // Sarah
 

In the above example, Object.defineProperty() is used to access and change the property of an object.

The syntax for using Object.defineProperty() is:

Object.defineProperty(obj, prop, descriptor)

The Object.defineProperty() method takes three arguments.

  • The first argument is the objectName.
  • The second argument is the name of the property.
  • The third argument is an object that describes the property.

 

 

 

 

Sources

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

 

Working with objects - JavaScript | MDN

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

developer.mozilla.org

https://www.javascripttutorial.net/javascript-bind/

 

JavaScript bind() Method and Its Practical Applications

In this tutorial, you will learn about the JavaScript bind() method and how to apply it effectively.

www.javascripttutorial.net

https://www.javascripttutorial.net/javascript-apply-method/

 

JavaScript apply() Method By Practical Examples

In this tutorial, you'll learn about the JavaScript apply() method of the Function type and how to use it effectively.

www.javascripttutorial.net

https://www.javascripttutorial.net/javascript-call/

 

JavaScript call() Method and Its Practical Applications

In this tutorial, you will learn about the JavaScript call() method and how to apply it in various contexts.

www.javascripttutorial.net