티스토리 뷰

모든 Object Prototype 을 갖는다.

var a = {};

//Firefox 3.6 and Chrome 5
Object.getPrototypeOf(a); //[object Object]

//Firefox 3.6, Chrome 5 and Safari 4
a.__proto__; //[object Object]

//all browsers
a.constructor.prototype; //[object Object]


Prototype 상속 받아 사용 할수 있다

//unusual case and does not work in IE var a = {}; a.__proto__ = Array.prototype; a.length; //0 //function will never be a constructor but it has a prototype property anyway Math.max.prototype; //[object Object] //function intended to be a constructor has a prototype too var A = function(name) { this.name = name; } A.prototype; //[object Object] //Math is not a function so no prototype property Math.prototype; //null

예제

//생성자 

var Circle = function(radius) {
    this.radius = radius;
    //next line is implicit, added for illustration only
    //this.__proto__ = Circle.prototype;
}

//augment Circle's default prototype property thereby augmenting the prototype of each generated instance
Circle.prototype.area = function() {
   return Math.PI*this.radius*this.radius;
}

//create two instances of a circle and make each leverage the common prototype
var a = new Circle(3), b = new Circle(4);
a.area().toFixed(2); //28.27
b.area().toFixed(2); //50.27

var A = function(name) {
    this.name = name;
}

var a = new A('alpha');
a.name; //'alpha'

A.prototype.x = 23;

a.x; //23

prototype 활용

String.prototype.times = function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
}

"hello!".times(3); //"hello!hello!hello!";
"please...".times(6); //"please...please...please...please...please...please..."

'웹개발 > Javascript' 카테고리의 다른 글

자바스크립트 정규 표현식  (0) 2010.12.23
자바스크립트 시간 계산 샘플  (1) 2010.12.20
Javascript Namespace 정리  (0) 2010.12.14
Javascript RegEx Api  (0) 2010.12.14
Javascript 키워드 몇가지  (0) 2010.12.14
댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함