10) 자바스크립트 X ES -1 (variable, prototype, Function, this)

0. Intro

리액트 문법을 중 class를 이해하기 위한 포스팅

자바스크립트 X 리액트

1. variable

prototype을 이해하기 위한 개념!

1-1. 원시타입

// 원시타입은 변수에 값을 재할당 해도 값이 변하지 않음
let a = 1
let b = a
b = 100
console.log(a) // 1

boolean

null

undefined

number

string

symbol

1-2. 참조타입 { 객체 }

c에서 포인터의 개념과 함께 이해하기!

// 참조타입은 변수가 같은 값을 참조하기 때문에 b를 조작해도 a도 바뀜
let a = [1, 2, 3]
let b = a
b.splice(0, 1)
console.log(a) // [2,3]

이런 참조타입 특성은 불변성 유지 개념과 맞물림.

1. 객체는 속성과 메소드를 갖는 독립적 주체이다.

객체의 형태

var obj = {
    // 속성
    property : "property",

    // 메소드
    method: function() {}
    // 혹은
    method() {}
}

2. 원시타입 제외하고 모두 객체다.(함수, 배열 등등)

인스턴스 🍎

인스턴스 객체는 함수에 의해 생성된다.

// ⭐ Object 생성자 함수
var obj = {}
var obj = new Object()

var obj2 = { name: '태니' }
var obj2 = new Object({ name: '태니' })

위의 용법도 Object 생성자함수의 인스턴스 객체를 의미한다.

함수 🍎

❓ 함수는 실행가능한 객체이다!
  1. A function is a subprogram designed to perform a particular task.

함수는 특정한 일을 수행하기위한 서브프로그램이다.

  1. Functions always return a value. In JavaScript, if no return value is specified, the function will return undefined.

함수는 항상 리턴값을 갖는다.

  1. Functions are objects.

함수는 객체이다.

  1. Functions execute when the function is called. This process is known as invocation. You can invoke a function by referencing the function name, followed by an open and closed parenthesis: ().

함수는 함수객체를 참조하는 이름과 ()로 함수를 호출하고 함수는 실행된다.

출처

배열 🍎

c에서 포인터의 개념과 함께 이해하기!

배열은 원시타입의 참조값이 들어있거나 객체(참조타입)의 참조값이 들어있다!

var arr = [1, 2, 3, 4]
var arr2 = [{}, {}, {}, {}]

2. prototype

프로토타입은 class를 이해하기 위한 개념!

2-1. Object 생성자함수

// ⭐
var obj = {}
var obj = new Object()
// 위에 두개는 똑같다. 리터럴이라고도함.

Object는 자바스크립트 내장 생성자함수이며 자바스크립트의 모든 인스턴스 객체들은 Object생성자 함수의 인스턴스이다. (조상님 Object)

2-2. Object.prototype

// ⭐
var obj = {}
obj.prototype // x
// 인스턴스 객체는 생성자함수의 속성인 prototype 속성에 접근불가
var a = function() {}
a.prototype // o
// 프로토타입은 생성자함수만 가지고 있다.
// ⭐
Object.prototype.name. = '태니' // (뒤에.은 뺌)
var obj4 = {}
obj4.name // 태니
// 쉽게 말해 객체 속성을 상속순으로 올라가며 탐색함. (원형객체까지)
// ⭐ use strict로 끊어줄 수도 있음

Object.prototype 속성은 모든 생성자함수에 상속된다.

prototype : 사전적의미의 프로토타입으로 이해하면 쉬운데, 생성될 인스턴스 객체의 형태를 담고있음.

즉, prototype 속성은 원형객체를 참조한다. (c의 포인터 느낌으로 메모리 소비 없이 원형객체 속성에 접근가능)

즉2, 생성될 모든 인스턴스 객체들은 prototype이 참조하는 원형객체를 참조함.

2-3. Object.prototype.constructor // obj.constructor

prototype 객체 내부에는 constructor 속성이 있다.

constructor : 인스턴스 객체의 프로토타입을 만든 생성자 함수를 참조.

// 생성자 함수
function taeny() {
  // ⭐ 생성될 인스턴스 객체 속성 부여
  this.name = '태니'
}

// 인스턴스 생성!
var today_taeny = new taeny()
var tomorrow_taeny = new taeny()

console.log(taeny.constructor)
// Function() {native code}
// ⭐ 너는 생성자함수인데 constructor가 있네?
console.log(today_taeny.constructor)
// taeny {this.name: '태니'}

2-4. __proto__

__proto__ : 인스턴스 객체가 생성될 때 조상이었던 함수의 prototype 객체(원형객체)를 참조

🐥 프로토타입 체이닝

❓ 현재 __proto__는 deprecated 되었다. 왤까?

3. Function 생성자함수 ⭐

Function생성자함수는 자바스크립트 내장객체로 모든 함수 인스턴스 객체를 생성하는 함수 객체이다.

function add(x, y) {
  return x + y
}

var add = new Function('x', 'y', 'return x+y;')

💡 add함수도 Function 함수의 하나의 인스턴트 객체이다.

4. this

this는 class를 이해하기 위한 개념!

예제는 출처 에서 많이 참고하였다.

4-1. this?

JAVA 에서의 this는 클래스의 생성될 인스턴트 객체를 의미한다.

javascript 에서의 this는 실행컨텍스트 내의 호출자를 의미한다.

비슷한 거 같으면서 비슷하지 않은 너.. this

const obj = {
  prop: 'obj의 값',
  inner: function() {
    console.log(this.prop) // 'obj의 값' 출력
  },
}
obj.inner()

실행컨텍스트>this

💡 제발 scope chain과 this 헷갈리지 말자!

브라우저 환경의 경우 this 에는 전역객체 window가 this에 담기고, nodeJS환경의 경우, this에는 해당 모듈을 가리킨다. 근데 console객체를 쓸 수 있는 이유는 window.console, global.console 처럼 scope chain 탐색을 통해 전역객체를 호출해서 쓰기 때문!!!!!!!!!!!

즉, 해당 객체의 메소드를 쓰기위해 해당 객체를 호출해서 메소드를 쓰는 순간!! 그 메소드(함수) 실행 컨텍스트 this에 그 해당 객체가 담긴다.

위의 경우, obj객체를 호출해서 inner 메소드를 사용하였다. inner안에 있는 함수의 호출자this는 obj가 된다.

4-2. use-strict 에서 this

function nonStrictMode() {
  return this
}

function strictMode() {
  'use strict'
  return this
}

console.log(nonStrictMode()) // window
console.log(strictMode()) // undefined
console.log(window.stricMode()) // window

‘use strict’ 모드에서는 현재 this의 값이 null 또는 undefined인 경우 전역 객체를 변환하지 않는다.

잘 이해해야한다!

4-3. 생성자 함수와 객체에서의 this

function NewObject(name, color) {
  this.name = name
  this.color = color
  this.isWindow = function() {
    return this === window
  }
}

const newObj = new NewObject('nana', 'yellow')
console.log(newObj.name) // nana
console.log(newObj.color) // yellow
console.log(newObj.isWindow()) // false

const newObj2 = new NewObject('didi', 'red')
console.log(newObj2.name) // didi
console.log(newObj2.color) // red
console.log(newObj2.isWindow()) // false

생성자 함수에서 this는 생성될 인스턴스 객체의 호출자를 미리 정해주는 개념이다.

만약 나를 통해 생성된 this(인스턴스 객체)의 name은 이걸로 해라~


Written by@taenyKim
배우며 성장하고 기록하기 #FE #UI #개발 #life

GitHubFacebook