ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JS]This
    JavaScript 2018. 1. 7. 15:49

    전역객체는 모든 객체의 유일한 최상위 객체를 말한다.

    Browser에서는 window, Node,js에서는 global 객체를 말한다.


    //Browser 

    this === window;    //true


    //Node

    this === global;    //true




    전역객체는 전역변수를 프로퍼티로 소유한다.


    ex) 

    var i = 'Kim';


    console.log(window.i);    //Kim




    생성자 함수를 호출할 때는 new 연산자가 붙어야 한다.

    new 연산자와 함께 호출되었는지 체크를 해주고 반환해주는 패턴이다.


    //Scope Safe Constructor Pattern

    var CommonCtrl = function(arg){

    //생성자 함수가 new 연산자와 함께 호출되면 빈 객체가 생성된다.


    /*

    arguments.callee는 호출된 함수의 이름이다.

    나 자신의 인스턴스가 CommonCtrl이 아닐 경우 return 값에 new 연산자를 넣어서 다시 호출해준다.

    */

    if (!(this instanceof arguments.callee)) {

    return new arguments.callee(arg);

     }

    this.value  = arg ? arg : 0;

    };


    CommonCtrl.prototype = {


     };


    var _commonctrl = new CommonCtrl(100);

    var _test = CommonCtrl(10);


    console.log(_commonctrl.value);    //100

    console.log(_test.value);    //10



    call method의 첫번째 인자는 함수 내부의 this에 바인딩할 객체를 넣어준다.

    두번째 인자는 함수에 전달할 인자를 넣어준다.


    //call method

    var Person = function(name) {

    //call method의 첫번째 인자 wook 객체를 Person의 this에 바인딩 시켜줬기 때문에 여기서 this는 wook객체가 된다.

    //그러므로 wook.name = name 이 된다.

    this.name = name;

    };


    var wook = {


    };


    Person.call(wook, 'Kim');

    console.log(wook);

    console.log(wook.name);

    댓글

Designed by Tistory.