티스토리 뷰

6장. 객체지향 프로그래밍

공통된 함수 객체(메서드)를 객체마다 생성하면 메모리 낭비

프로토타입 객체에 함수를 정의하자.

더글라스 크락포드식 메서드 정의 방법

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
}

function Person(arg) {
    this.name = arg;
}

Person.method("setName", function (value) {
    this.name = value;
})

Person.method("getName",function () {
    return this.name;
})

let me = new Person("me");
let you = new Person("you");
console.log(me.getName());
console.log(you.getName())

프로토타입을 이용한 상속

자식 객체 생성: create_object (Object.create())

자식에 메서드 추가 extend (shallow copy version)

클래스 기반의 상속

중개자

'자바스크립트 패턴'에 소개된 최적화된 상속 코드

let inherit = function (Parent, Child) {
    let F = function () {};
    return function (Parent, Child) {
        F.prototype = Parent.prototype;
        Child.prototype = new F();
        Child.prototype.constructor = Child;
        Child.super = Parent.prototype;
    };
}();

캡슐화 (정보 은닉)

(패턴, 단점) 나열

모듈 패턴

6.4 subClass 함수 구현하기 -> 나중에

 

7장. 함수형 프로그래밍

메모이제이션

cache 프로퍼티 혹은 data 객체(key - value형식)등을 만들고 이를 참조하는 함수(클로저)를 리턴하는 함수를 만들면, 메모이제이션이 가능하다.

Function.prototype에 메모이제이션 함수를 집어넣으면 모든 함수에서 키-결과 캐싱을 사용할 수 있다.

 

커링

정의된 인자 일부를 넣어 고정시키고, 나머지를 인자로 받는 새로운 함수를 만드는 것

자바스크립트 기본지원X

//Function.prototype에 정의하고 사용

Function.prototype.curry = function() {
    let fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
        return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
    }
}

원하는 위치를 고정하는 curry 함수

<코드블럭>

 

bind

let myFunc = myOriginFunc.bind(objectToBindAtThis, arguemntToBind1, ..);
myFunc(argumentRemaining1, ..);

고정시키고자 하는 인자를 넘겨주고 반환받은 함수를 호출하면서 나머지 가변 인자를 넣을 수 있음

this에 바인딩시킬 객체도 넣어줄 수 있음

 

wrapper

function wrap(object, method, wrapper) {
    let fn = object[method];
    return object[method] = function () {
        return wrapper.apply(this, [fn.bind(this)].concat(Array.prototype.slice.call(arguments)));
    }
}

Function.prototype.original = function (value) {
    this.value = value;
    console.log(`value: ${this.value}`);
}

let myWrap = wrap(Function.prototype, "original", function (orig_func, value) {
    this.value = 20;
    orig_func(value);
    console.log(`Wrapper value : ${this.value}`);
});

let obj = new myWrap("KIMCHI");

 

 

반복 함수

each/forEach

map

reduce

구현은 나중에 보자

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함