JavaScript: Class.method vs. Class.prototype.method

-- JavaScript 2017. 1. 25. 13:34
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
자바스크립트에서 객체를 사용할 때 메소드의 타입에 대해서 설명한 글이 있어 정리해둔다.

추가) 2017-01-26
"3 ways to define a JavaScript class" 글의 내용을 추가


1. Using a function


[CLASS]


function MyClass () {
// private member only available within the constructor fn (???)
var privateVariable; 

// TYPE1: it can access private members (???)
// [ Methods defined internally ]
this.privilegedMethod = function () {};
}

// TYPE2: A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance

MyClass.staticMethod = function () {};

// TYPE3: the 'this' keyword refers to the object instance
// you can access only 'privileged' and 'public' members
// [ Methods added to the prototype ]
MyClass.prototype.publicMethod = function () {};


[USAGE]

var myObj = new MyClass(); 

// DOT NOTATION
myObj.privateVariable = 1;
myObj.privilegedMethod();
myObj.publicMethod();
MyClass.staticMethod();

// BRACKET NOTATION
myObj["privateVariable"] = 1;
myObj["privilegedMethod"]();
myObj["publicMethod"]();
myObj["staticMethod"]();


2. Using object literals

So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:

var apple = {
    type: "macintosh",
    color: "red",
    getInfo: function () {
        return this.color + ' ' + this.type + ' apple';
    }
}

In this case you don't need to (and cannot) create an instance of the class, it already exists. So you simply start using this instance.

apple.color = "reddish";
alert(apple.getInfo());

Such an object is also sometimes called singleton. In "classical" languages such as Java, singleton means that you can have only one single instance of this class at any time, you cannot create more objects of the same class. In JavaScript (no classes, remember?) this concept makes no sense anymore since all objects are singletons to begin with.


3. Singleton using a function

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object. Here's the syntax:

var apple = new function() {
    this.type = "macintosh";
    this.color = "red";
    this.getInfo = function () {
        return this.color + ' ' + this.type + ' apple';
    };
}
So you see that this is very similar to 1.1. discussed above, but the way to use the object is exactly like in 2.

apple.color = "reddish";
alert(apple.getInfo());

new function(){...} does two things at the same time: define a function (an anonymous constructor function) and invoke it with new. It might look a bit confusing if you're not used to it and it's not too common, but hey, it's an option, when you really want a constructor function that you'll use only once and there's no sense of giving it a name.



posted by 어린왕자악꿍