JavaScript OOP - 다중객체 생성 맛보기
ITWeb/개발일반 2011. 12. 16. 16:22그래서 다중객체 생성하는 방법에 대한 두 가지 접근 방법에 대해서 예제 코드를 작성해 보았습니다.
[Object 생성을 위한 Brace({}) 사용]
// Class 다중 생성 및 Linking 구조
var ClassSuper = {};
var ClassSuperWrap = function () {};
var classObj1, classObj2;
ClassSuper.key = 'KEY';
ClassSuperWrap.prototype = ClassSuper;
classObj1 = new ClassSuperWrap();
classObj2 = new ClassSuperWrap();
classObj1.prototype = ClassSuper;
classObj2.prototype = ClassSuper;
console.log(classObj1.key);
console.log(classObj2.key);
classObj1.key = 'KEY1 Changed';
console.log(classObj1.key);
console.log(classObj2.key);
classObj2.key = 'KEY2 Changed';
console.log(classObj1.key);
console.log(classObj2.key);
delete classObj1.key;
console.log(classObj1.key);
console.log(classObj2.key);
[Function 을 이용한 방법]
// Class 다중 생성 및 Linking 구조
var ClassSuper = function () {};
var classObj1, classObj2;
ClassSuper.prototype.key = 'KEY';
classObj1 = new ClassSuper();
classObj2 = new ClassSuper();
console.log(classObj1.key);
console.log(classObj2.key);
classObj1.key = 'KEY1 Changed';
console.log(classObj1.key);
console.log(classObj2.key);
classObj2.key = 'KEY2 Changed';
console.log(classObj1.key);
console.log(classObj2.key);
delete classObj1.key;
console.log(classObj1.key);
console.log(classObj2.key);
※ 눈치 빠르신 분들은 아시겠지만 fake 입니다.. ^^; (그냥 다른 방법 이라고 보시는게 맞겠죠..)
누가 번거롭게 첫번째 방식으로 하겠냐고 하실 수도 있으나 할 수 있습니다..
뭐.. 코딩 하는 사람 맘 아니겠습니까!!
그럼 크롬에서 찍힌 로그를 확인해 볼까요.
아래 결과 첨부 합니다.
// 첫번째 로그 결과
// 두번째 로그 결과
[참고링크]
- http://www.danielbaulig.de/now-thats-class-its-an-object-prototypal-inheritance-in-javascript/
[원문 Scrap]
Now that’s class, it’s an object! – Prototypal Inheritance in JavaScript
JavaScript is an object oriented programming language like most programming languages nowadays. However, unlike most programming languages it does not use the concept of classes. Instead from classes objects inherit directly from other objects, their so called prototypes. If you’re familiar with a traditional object oriented programming language like Java or C++ and / or if you already have fundamental knowledge of JavaScript, then this article is directed at you.
In the beginning there was Object.prototype
To fully understand how object oriented JavaScript works, you will have to abandon any concept of object orientation you know. Yes, forget it. You won’t need it, and I will teach you anew. JavaScript object orientation works quite differently than in most other languages, you will only get confused about what is going on in JavaScript if you try to apply your old concepts and ideas of object orientation to JavaScript. So forget about it. Done? Good. So now that you forgot, let me introduce you to the object:
This is what we call an object literal in JavaScript. It is the most basic form of an object and works similar to array literals in other languages. You may have noticed that there is no reference to a class. – Didn’t I tell you to forget everything you know about other object oriented languages?! That certainly includes classes! – Whatever, there are no classes in JavaScript. Objects in JavaScript do not inherit from classes, but from other objects, their so called prototypes. If an object does not have an explicit prototype, like in the case of an object literal, it will inherit from a special built-in object, which is accessible throughObject.prototype
.
Objects in JavaScript are dynamic hashmaps. A hashmap is a set of key/value pairs. For each value in an object, like an attribute or a method, there is a key, that identifies that value and allows access to it. You can access an object member with the dot operator followed by the literal key (dot notation) or by enclosing the key in string form in index brackets (bracket notation):
If you think the bracket notation looks a lot like accessing arrays then this is because arrays in JavaScript basically are nothing but objects with integer attribute keys.
Because objects are dynamic, you can add and remove any member at runtime, even after the object was created. You add a member by simply assigning to it and your remove it by using the delete
operator on the member:
Also, when you create an object using an object literal, you can add an arbitrary amount of attributes and methods to it, by listing key/value pairs, separated by comma and split by a colon:
Defining objects this way is very cool and singlehandedly eliminates the need for the singleton pattern, but it can be very tyring if you require multiple objects with the same attributes over and over again. What you want is a method that makes creating similar objects easy. Luckily JavaScript provides such a method.
Crock’ the Constructor
For easier object instantiation JavaScript provides the new
keyword. Calling any function with a prepended new
keyword will turn this function into a constructor function. Constructor functions basically work like normal functions with the difference that their this
keyword will be bound to a newly created object and they will automatically return this newly created object if there is no explicit return statement. Although you could turn any arbitrary function into a constructor function using the new
keyword, this does not make much sense in most cases. Usually you build special functions that will be used exclusively as constructor functions. By convention those functions start with a capital letter.
What this constructor function does is implicitly create a new object and bind it to the functions this
identifier. Then the function body is executed, which will create a message
attribute, a count
attribute and a printMessage
method on the new object. Since there is no explicit return statement, the new object, augmented with it’s new members, will be returned implicitly.
Note though, that this construct is not a class. There are no classes is JavaScript. This is simply a function which adds members to a new object. The style of calling it might look a bit like a class constructor in other languages, but I told you: forget about what other languages do.
But there is a problem with this example. Not with constructor functions in general, but because we used a very naive variant. Each time we call this constructor function it will create a new object with a message
and a count
attribute. Up until here this is fine, but it will also create a new anonymous function and add it as a method to the object each timeyou call the constructor function. This means, that each object will get it’s own, separate function, which will require it’s own memory, it’s own compilation time, etc. While this >might> be what you want, it’s most likely not. What you actually want are several objects that all use the exact same function. Prototypes are what enables this in a very easy way.
Honor, guide me!
Prototypes are JavaScript’s way of inheritance. Each object in JavaScript has exactly one prototype. There are several ways to declare a newly created object’s prototype (and some implementations even allow the prototype to be changed after object instantiation), but let us look at how exactly prototypes work first.
When you read a member from an object, JavaScript will look for this member on the object itself first. If JavaScript cannot find the member on the object, it will go to the objects prototype and see if it can find the member there. If it fails again it will proceed to move along the prototype chain until it either finds the member on one of the prototype objects, in which case it will return it’s value or has reached the end of the chain without finding the member on any of the objects on the prototype chain. In that case undefined
is returned.
If you write an object’s member by assigning to it, JavaScript will always set the objects own member. When assigning a member, JavaScript will never alter any object on the prototype chain. This is possible however, you will only need to do it explicitly. The following code will demonstrate what I just explained. Note that p
is set as o
‘s prototype.
I just introduced you to the first method of setting an objects prototype:Object.create(prototype);
. Object.create
returns an empty object with it’s prototype set to whatever object you pass in. Object.create
can do more, but this is out of scope for this article.
When using an object literal you cannot specify a prototype for your object. The syntax simply doesn’t give you the tools to do so (although this might come in a future ECMAScript version). However, when using the constructor function pattern, you can specifiy the prototype of the created object. This is done by setting the prototype
attribute of the constructor function. Whenever the function is called using the new
keyword, the returned object will have it’s prototype set to whatever the value of the constructor functions prototype attribute was at the time:
With this pattern, you can now create an arbitrary amount of Things, which all inherit from p
. All those Things share the exact same methods and attributes. Whenever you call a Thingsmethod
method, it will call the exact same function p.method
(that is as long as you do not explicitly set the Things members to something else). So in comparison to our first try with using the constructor function, we will save memory, compilation time, etc, becausemethod
exists only once, on the prototype p
.
Busfactor
You now basically know everything you need to know about object oriented JavaScript. The rest is forging this knowledge into practically usable patterns. The following code is a small example how an object oriented system could be created using JavaScript prototypal inheritance. Be aware, that there are multiple patterns to do object orientation in JavaScript. Some embrace the prototypal nature of JavaScript, while others try to mimic what JavaScript people call classical object orientation.
Personally I don’t like classical patterns as much (especially those that try to mimic information hiding and private methods and attributes), since most will make your code slow and clunky. The following pattern is a good balance I think. It is aware of JavaScripts prototypal model, but people coming from a classical model will be able to grasp what it does.
JavaScript is all about functions and objects. That’s all what’s to it, even in it’s inheritance model. I hope you enjoyed this article. If you have any further questions or would like to comment, please do so below. If you want to learn more about JavaScript come back soon, to learn more about the secrets of closures, scope and functions. You can also subscribe tothe feed, to stay tuned. Or, if you are in a hurry and want some good lecture, you should definitly check out Douglas Crockfords “JavaScript: The Good Parts” (Amazon Affiliate Link).