2016년 12월 14일 수요일

Javascript static function example

Javascript static 함수/변수 선언 예


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Javascript static function demo</title>
<script type="text/javascript">
function Vector2D(x,y) {
     
    this.x = x;
    this.y = y;
     
    // 인스턴스 함수 선언
    this.add =  function(v2d){
        var x = this.x + v2d.x;
        var y = this.y + v2d.y;
        return new Vector2D(x,y);
    }
};
 
// static 변수선언
Vector2D.len = 0;
 
// static 함수 선언
Vector2D.add = function(v1,v2) {
    //alert(this.x); // this.x 를 인식하지 못함
    return new Vector2D(v1.x+v2.x, v1.y+v2.y);
}
 
// 인스턴스 함수 추가선언
Vector2D.prototype.length = function() {
    return Math.sqrt(this.x*this.x + this.y*this.y);
}
 
// 인스턴스 변수 추가선언
Vector2D.prototype.name = 'MyName'; // 이미 생성된 인스턴스에도 포함됨
 
<!-- var v2d = new Vector2D(3,4); -->
var tmp = new Vector2D(1,2);
var resultVec = v2d.add(tmp); // 인스턴스 함수호출
//console.log(resultVec.x);
 
var vec = Vector2D.add(v2d,tmp); // static 함수호출
 
console.log('v2d.length():'+v2d.length()); // 인스턴스 함수호출
console.log('Vector2D.len:'+Vector2D.len); // static 변수사용
 
</script>
</head>
<body>
 
</body>
</html>


댓글 없음: