퇴근5분전

 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  /*  http://javascript.info/tutorial/pseudo-classical-pattern
    There is a well-known, but wrong way of inhereting, when instead of Rabbit.prototype = inherit(Animal.prototype) people use: 
// inherit from Animal  
Rabbit.prototype = new Animal()  
As a result, we get a new Animal object in prototype. Inheritance works here, because new Animal naturally inherits Animal.prototype. 
… But who said that new Animal() can be called like without the name? The constructor may strictly require arguments and die without them. 
Actually, the problem is more conceptual than that. We don’t want to create an Animal. We just want to inherit from it. 
That’s why Rabbit.prototype = inherit(Animal.prototype) is preferred. The neat inheritance without side-effects.  
    */
     
    function inherit(proto) {
        function F() { }
        F.prototype = proto;
        return new F;
    }
    //상속 관련!
    function extend(Child, Parent) {
        Child.prototype = inherit(Parent.prototype);
        Child.prototype.constructor = Child;
        Child.parent = Parent.prototype;
    }
    // todo : 네임스페이스

    var JS = {};
    JS.Pet = function (name) { this.getName = function () { return name; } };
    var pet = new JS.Pet("애완");

    JS.ExpendClass = {}; // 하나더..
    JS.ExpendClass.Dog = function (name) { JS.Pet.apply(this, [name]); };
    
    extend(JS.ExpendClass.Dog, JS.Pet);

    var dog = new JS.ExpendClass.Dog("강아쥐!!!");
    
    alert(pet.getName());
    alert(dog.getName());

    //네임스페이스가 길어지면 힘들어짐... 그래서 별칭도 가능함.
    var JSExc = JS.ExpendClass;

    JSExc.Cat = function (name) { JS.Pet.apply(this, [name]); }
   
    extend(JSExc.Cat, JS.Pet);

    var cat = new JSExc.Cat("냐옹이!!");
    alert(cat.getName());

     

 

네임스페이스 관련된 내용을 적어본다. 

 

var JS = {}; // object 선언

var JS.ExpendClass = {}; // object 선언

// static 을 이용해서 네임스페이스처럼 쓰는 것임.

'# 6) JavaScript' 카테고리의 다른 글

javascript] OOP정리. override  (0) 2014.05.23
javascript] OOP정리. 상속  (0) 2014.05.23
javascript] OOP정리. static 멤버  (0) 2014.05.23
javascript] OOP정리. prototype  (0) 2014.05.23
javascript] OOP정리. class처럼 만들기.  (0) 2014.05.23