TIL day2 Object 두번째

Winney·2020년 8월 11일
0

Javascript 개념

목록 보기
2/8

1. The 'this' keyword

Object are collections of related data and functionality. We store that functionality in methods on our objects:

const dog = {
	dietType: 'omnivores',
    makeSound () {
    	console.log('Wang Wang');
    },
    diet() {
    	console.log(dietType);
    }
};

dog.makeSound(); // Return 'Wang Wang'
dog.diet(); //Output: "ReferenceError: dietType is not defined"

ReferenceError의 이유: That's because inside the scope of the .diet() method, we don't automatically have access to other properties of the dog object.
-> diet() scope을 벗어나기 때문에 dietType에 접근 할 수 없다.

...
    diet() {
    	console.log(this.dietType);
    }
...
console.log(dog.diet()); // Return 'omnivores'

참고 https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3

2. Arrow Functions and this

const dog = {
	dietType: 'omnivores',
    makeSound () {
    	console.log('Wang Wang');
    },
    diet: () => {
    	console.log(this.dietType);
    }
};
console.log(dog.diet); // Return undefined

Arrow functions inherently bind, or tie, an already defined this value to the function itself that is NOT the calling object.
In the code snippet above, the value of this is the global object, or an object that exists in the global scope, which doesn’t have a dietType property and therefore returns undefined.

3. Privacy

Accessing and updating properties is fundamental in working with objects. However, there are cases in which we don't want other code simply accessing and updating and object's properties. When discussing privacy in objects, we define it as the idea that only certain properties should be mutable or able to change in value.

Javascript는 privacy를 위한 기능이 없다. 그래서 javascript developers 일반적으로 사용되는 conventions는 (underscore)이다.
해당 property name(key)앞에
를 붙여 privacy를 표시해준다.

const user = {
	ID: 'victory',
    _password: 1234
};

user._password = 4321;
// ressign 가능함.

4. Getter

Getter are methods that get and return the internal properties of an object. But they can do more than just retrieve the value of a property!

const person = {
  _firstName: 'xia',
  _lastName: 'Jou',
  get fullName() {
    if (this._firstName && this._lastName){
      return `${this._firstName} ${this._lastName}`;
    } else {
      return 'Missing a first name or a last name.';
    }
  }
};

// To call the getter method: 
person.fullName; // 'John Doe'
  • We use the get keyword followed by a function
  • We use an if...else conditional to check if both _firstName and _lastName exist(true) and then return a diffenrent value depending on the result.
  • We can access the calling object's internal properties using this. In fullName, we're accessing both this._firstName and this._lastName.
  • In the last line we call fullName on person. In general, getter methods don't need to be called with a set of paretheses. Syntactically, it looks like we're accessing a property.

Adventage of using getter methods

  • Getters can perform an action on the data when getting a property.
  • Getters can return different values using conditionals.
  • In a getter, we can access the properties of the calling object using this
  • The functionality of our code is easier for other developers to understand.

getter/setter function은 같은 이름을 사용 할 수 없다. 만약 같은 이름을 사용 할 경우 an infinite call stack error가 발생한다.

5. Setter

Along with getter methode, we can also create setter method which reassign valuew of existing properties within an objects.

const person = {
  _age: 37,
  set age(newAge){
    if (typeof newAge === 'number'){
      this._age = newAge;
    } else {
      console.log('You must assign a number to age');
    }
  }
};

person.age = 40;
console.log(person._age); // Logs: 40
person.age = '40'; 
// Logs: You must assign a number to age

Like getter methods, there are similar advantages to using setter methods that include checking input, performing actions on properties, and displaying a clear intention for how the object is supposed to be used.
Nonetheless, even with a setter method, it is still possible to directrly reassign properties. For example, in the example above, we can still set ._age directly

person._age = 'forty-five'
console.log(person._age); // Prints forty-five

6. Factory Functions

Factory Functions can create many instances of an object quickly.
Factory Function is a function that returns an object and can be reused to make multiple object instances.
Factory Functions can also have parameters allowing us to customize the object that gets returned.

const monsterFactory = (name, age, energySource, catchPhrase) => {
  return { 
    name: name,
    age: age, 
    energySource: energySource,
    scare() {
      console.log(catchPhrase);
    } 
  }
};

monsterFactory has four parameters and returns an object that has the properties: name, age, energySource, scare()

const ghost = monsterFactory('Ghouly', 251, 'ectoplasm', 'BOO!');
ghost.scare(); // 'BOO!'

To make an object that represents a specific monster like a ghost, we can call monsterFactory with the necessary arguments and assign the return value to a variable.

7. Property Value Shorthand(ES6)

// truncated version
const monsterFactory = (name, age) => {
  return { 
    name: name,
    age: age
  }
};

// property value shorthand (ES6)
const monsterFactory = (name, age) => {
  return { 
    name,
    age 
  }
};

8. Destructured Assignment

We often want o extract key-value pairs from objects and save them as vatiables.

const vampire = {
  name: 'Dracula',
  residence: 'Transylvania',
  preferences: {
    day: 'stay inside',
    night: 'satisfy appetite'
  }
};

//Extract key-valuew pairs
const residence = vampire.residence; 
console.log(residence); 
// Prints 'Transylvania' 

Howevers, we can also take advantage of a destructuring technique called destructured assignments

const { residence } = vampire; 
console.log(residence); 
// Prints 'Transylvania'

Destructured assingment can grab nested properties of an object

const { day } = vampire.preferences; 
console.log(day); 
// Prints 'stay inside'

9. Built-in Object Methods

1. Instance methods

참조 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods

2. Static methods(object class method)

참조 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods_of_the_Object_constructor

profile
프론트엔드 엔지니어

0개의 댓글