메뉴 건너뛰기

조회 수 5369 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

 

[ 함수호출연산자 ]

()연산자는 함수 호출하는데 사용하며...
첫번째 피연산자는 함수이름 또는 함수리터럴이 오고 두번째 피연산자는 () 내에 파라메터값이 쉼표로 구분해서 온다...()호출연산자는 첫번째 지정한 함수를 호출한다.

함수는 하나의 데이터 타입이며...함수명은 함수리터럴의 레퍼런스이다.
고로 일반 변수처럼 배열,객체 프로퍼티,파라메터 등등 자유롭게 사용할수 있다.

( function(x,y){ alert(x+','+y); } )(1,2);

// ()호출연산자는 두번째 피연산자와 함께, 첫번째 피연산자인 함수리터럴을 호출한다.
//물론 함수명이 오면 해당 레퍼런스를 호출한다.. 앞에 ()는 호출연산자가 아니라 그룹화시킨것 뿐이다.



 

function test( x ){
      var an=1; //함수내 지역변수.
      alert( typeof test +','+ typeof test.prototype +','+ typeof this); // function , object , object
      alert( this instanceof Window ); // true , 함수리터럴이 자동으로 전역객체에 추가되기때문..
}
test();
alert(typeof test); //function

test.bn = 2; //정적멤버변수 설정
alert(test.an +","+ test.bn );  // undefined, 2
alert(test.length +','+ test.toString() );  // 1, function test( x ){ ...}
alert( (new test()).an +","+ (new test()).bn);  // undefined, undefined

// 정적변수나 정적함수는 함수명(클래스명)으로 외부에서 추가하고 참조할수 있다.
// 만약 객체를 생성하더라도 정적변수와 함수는 객체와는 무관하며, 모든 객체에 참조가능한 멤버변수 및 함수를 만들려면 prototype을 사용한다.
// prototype은 함수선언시 자동생성되는 객체로, 함수명(클래스)으로 선언, 모든 객체에서 참조가능하다. 일종의 상속

++++

var y = new Function("x","return Math.sin(x)")
y.yy = function(){alert('yy');}
y.yy();
alert( Math.ceil(y(360)) );
alert(y);

++++

var o = {_an:1,_bn:2} //무명객체이기땜시 프로퍼티에 this를 쓰면 참조불가능
alert(o._an +","+ o._bn);  // 1, 2

function o(){
      var aa= 1;
      this._an = 1; //사용자 정의 객체 프로퍼티에서 aa는 지역변수임
      this._bn = ofunc;
}
function ofunc(){ return 2}
alert( (new o())._an +','+ (new o())._bn() );

++++

var y = "global";
function testFunction() {
    var y = "local";
    return new Function("return y");  // Function객체는 top-level에서 컴파일되므로 지역변수를 참조할수 없다.
}
alert( testFunction()() ); //global 출력

++++

function f(x,y){ return x+y }
alert( f.apply( {},[1,2] ) );  // f 함수를 무명객체의 메소드처럼 호출한다. 즉 {}.f(1,2)와 같다
alert( f.call( {},1,2 ) ); // 바로 위 문장과 동일하다.

++++

function f(x,y){
    alert(arguments.callee); // callee 함수 자신참조
    return x+y
}
f(1,2);


 



[ 정적 클래스 ]

//정적 클래스
var staticClass = (function(){
    var cnt = 0; //지역변수 한번만 실행됨. 초기화용
    return {
        staticMethod:function(){ return cnt++; }
      }
})();
document.write(staticClass.staticMethod()); // 0 출력
document.write(staticClass.staticMethod()); // 1 출력

//일반 클래스 + 정적 클래스
var staticClass = (function(){
    var name = "테스트"; //지역변수
    function init(name){
        this.name = name; //멤버변수설정
    }
    init.staticMethod = function(){
        return "staticMethod "+name;
    }
    init.prototype = { //init함수의 prototype설정
        noStaic1:function(){
            return "noStaic1 " + this.name;
        },
        noStaic2:function(){
            return "noStaic2 " + this.name;
        }
    }   
    return init;
 })();

//정적메소드에 접근
alert(staticClass.staticMethod());

//클래스 인스턴스 생성 후 메소드에 접근
var obj = new staticClass("test");
alert( obj.noStaic1() );

++++
다른 예..
function car(m) {
    this.model = m
    this.staticFunc = function(str){ //객체함수(클래스함수참조용)
        return car.myMethod(str); //클래스함수참조
    }
    //this.staticFunc = staticFunc;
}
function myMethod(str){ //클래스함수
    alert('myMethod : '+str);
}
function myMethod2(){
    alert('myMethod2');
}
//function staticFunc(str){return myMethod(str);}
car.myMethod = myMethod; //클래스함수추가
car.myMethod('test'); //클래스함수호출
car.prototype.maker = true;

var carObj1 = new car("Acura")
var carObj2 = new car("BMW")
carObj1.staticFunc('aaa');
carObj2.myMethod2 = myMethod2;
alert(carObj1.model +','+ carObj1.maker);
carObj1.myMethod2();
carObj2.myMethod2(); //error;


 



[ 변수의 블록범위가 없다 ]

변수 선언시 함수의 블록만 의미가 있을뿐..나머지 블록은 의미가 없다.

function test(o){
    var i = 0; // i는 함수전체에 걸쳐 정의된 지역변수
    if(typeof o == 'object')
    {
        var j = 0; // j도 if블록내가 아니라 함수전체에 걸쳐 정의된 지역변수
        for(var k=0; k<5; k++){ //k도 for블록내가 아니라 함수전체에 걸쳐 정의된 지역변수
            document.write(k);
        }
        document.write('-'+k);
    }
    document.write('-'+j);
}
test({});  // 출력 : 01234-5-0


 

var scope = "global";
function f() {
    alert(scope);      // scope는 함수내 선언된 지역변수 참조..값할당되기전 참조했으므로 undefined
    var scope = "local"; 
    alert(scope);
}
f();


 



[ 전역객체 ]

자바스크립트 인터프리터가 작동을 시작할때...임의의 스크립트코드를 실행하기전에 자바스크립트 내부에서 처음으로 수행하는 작업은 전역객체(global object)를 생성하는 것이다.
전역객체에는 미리정의된 모든함수와 프로퍼티가 들어 있다. 이 전역객체의 프로퍼티 및 함수는 자바스크립트 프로그램의 전역변수이므로 직접 전역객체를 참조하지 않고 바로 사용할 수 있다.
또한 우리가 자바스크립트코드에 전역변수와 함수를 선언하고 브라우저에 실행하면 실제로 전역객체의 해당 프로퍼티인 window객체에 자동으로 추가하는 것이다.

예를 들어 parseInt함수와 Math객체는 전역객체에 미리 정의된 parseInt,Math프로퍼티를 참조한다.
스크립트 코드에 사용자 함수와 변수는 해당 전역객체인 window객체에 자동추가된다.

즉, 클라이언트 자바스크립트에서는 전역객체로서 브라우저 내부를 나타내는 window객체를 사용한다.
우리가 작성하는 코드의 전역변수와 함수들은 window객체에 프로퍼티로 자동 추가된다.
또한 자기자신을 참조하는 window프로퍼티도 포함하고 있다. 이 프로퍼티를 this로 참조할 수 있고 직접  window를 사용할 수도 있다. 함수내에서의 this와는 다른의미다.

var test = function(){alert('test');}
var scope = 20;

for(var p in window){
    document.write(window[p]+'<br>');
}
//출력 : 아래와 같이 추가된 것을 알수 있다.
// 20
// function () { alert("a");}
// .......


 



[ 이벤트 ]

//Keyboard Events
function showKey(e) {
  var key;
  if (window.event) {
    key = window.event.keyCode;
  } else {
    key = e.keyCode;
  }
  key = String.fromCharCode(key);
  document.getElementById("para").innerHTML += key;
}
window.onload = function() {
  document.onkeydown = showKey;
}
<p id="para">Click and type here: </p>

//Mouse Events
function showPosition(e) {
  var x, y;
  if (window.event) { //IE
    x = window.event.clientX;
    y = window.event.clientY;
  } else { //FF
    x = e.pageX;
    y = e.pageY;
  } 
  //indow.status = "x: " + x + ", y: " + y;
  var key = "x: " + x + ", y: " + y;
  document.getElementById("para").innerHTML = key;
}
window.onload = function() {
  document.onmousemove = showPosition;
}
<div id="mstatus"></div>

//Extending Built-In Objects
function isLeapYear() {
  var y = this.getFullYear();
  return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
}
Date.prototype.isLeapYear = isLeapYear;
var d = new Date();
alert(d.isLeapYear());

//Form with the Enter Key
function checkKey(e) {
  var key;
  if (window.event) {
    key = window.event.keyCode;
  } else {
    key = e.keyCode;
  }
  if (key == 13) { // 엔터
    document.forms[0].submit();
  }
}
window.onload = function() {
  document.forms[0].elements["field"].onkeydown = checkKey;
}
<form><input name="field" type="text" /></form>


 



[ 상속 ]

function UniversalTranslator() {
  this.copyright = " copyright...";
}
function UniversalCounter() {
  this.Count = count;
  var numbers = {
    "en": "one, two, three",
    "fr": "un, deux, trois",
    "de": "eins, zwei, drei"
  };
  function count(language) {
    if (numbers[language]) {
      alert(numbers[language]+" [ " + this.copyright + " ]");
    } else {
      window.alert("Unknown language");
    }
  }
}
UniversalCounter.prototype = new UniversalTranslator();
var uc = new UniversalCounter();
uc.Count("de");

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved