1) 프로토타입 속성으로 부모 객체 참조
- <script>
- function Clothes(name, top, bottom, color) {
- this.name = name;
- this.top = top;
- this.bottom = bottom;
- this.color = color;
- this.print = function() {
- var out='';
- out+='name:'+this.name+'\n';
- out+='top:'+this.top+'\n';
- out+='bottom:'+this.bottom+'\n';
- out+='color:'+this.color;
- console.log(out);
- }
- }
- function Dress(name, top, bottom, color) {
- this.name = name;
- this.top = top;
- this.bottom = bottom;
- this.color = color;
- this.changeDress = function() {
- this.name = 'dress2';
- }
- }
- Dress.prototype = new Clothes();
- var dress = new Dress('dress', 95, 26, 'red');
- dress.print();
- </script>
를 호출하는 예제입니다.
2) 프로토타입 공유
- <script>
- function Clothes(name, top, bottom, color) {
- this.name = name;
- this.top = top;
- this.bottom = bottom;
- this.color = color;
- }
- Clothes.prototype.print = function() {
- var out='';
- out+='name:'+this.name+'\n';
- out+='top:'+this.top+'\n';
- out+='bottom:'+this.bottom+'\n';
- out+='color:'+this.color;
- console.log(out);
- }
- function Dress(name, top, bottom, color) {
- this.name = name;
- this.top = top;
- this.bottom = bottom;
- this.color = color;
- this.changeDress = function() {
- this.name = 'dress2';
- }
- }
- Dress.prototype = Clothes.prototype;
- var dress = new Dress('dress', 95, 26, 'red');
- dress.print();
- </script>
3) Object.create() 를 이용한 상속 구현
- <script>
- var clothes = {
- name:'dress',
- top:95,
- bottom:32,
- color:'black',
- print:function() {
- console.log(this.name+' '+this.top+' '+this.bottom+' '+this.color);
- // result : dress 95 32 black
- }
- };
- var dress = Object.create(clothes);
- dress.print();
- dress.price = 30;
- console.log(dress.price); // result : 30
- dress.printAll = function() {
- console.log(this.name+' '+this.top+' '+this.bottom+' '+this.color+' '+this.price);
- // result : dress 95 32 black 30
- };
- dress.printAll();
- </script>
댓글 없음:
댓글 쓰기