회원가입∴아이디/비번찾기
홈으로


자바스크립트
15년 전
[ 함수호출연산자 ]

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

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



( 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");
추천추천 : 412 추천 목록
번호 제목
2,891
입력 필드에서 특정단어(예:#err)가 포함되었을 때 실시간 감지 및 경고창 띄우기
2,890
데이터베이스 최적화와 쿼리 효율성을 높이 검색 성능을 개선하는 방법
2,889
간단한 게시판 만들기
2,888
PHP의 php.ini 파일에서 설정할 수 있는 주요 항목들을 카테고리별로 정리
2,887
유튜브 동영상의 썸네일 이미지를 체크하여 유효한 영상이아닐때 연결된 체크박스를 자동으로 체크
2,886
이미지 URL이 유효하지 않을 때, 해당 이미지와 연결된 체크박스를 자동으로 체크
2,885
HTTPS로 접속한 사용자를 강제로 HTTP로 리디렉션 하려면
2,884
PHP에서 MP3 파일을 직접 읽고 스트리밍 하기
2,883
현재 페이지가 location.reload()에 의해 새로고침되었는지
2,882
텍스트 파일을 읽고, 각 줄의 끝에서 6글자를 삭제한 후, 결과를 새로운 파일에 저장합니다.
2,881
cURL을 사용하여 리다이렉트를 따라가 최종 URL 가져오기
2,880
[PHP] $_SERVER 환경변수
2,879
10진수 <-> 16진수 변환기 PHP소스
2,878
텍스트에 직접 그라데이션 색상을 적용하려면?
2,877
CSS를 사용하여 요소의 내용물에 따라 width를 조정하는 방법
2,876
웹서버 ip 확인
2,875
웹호스팅의 절대경로를 확인
2,874
input 입력 필드 앞뒤 공백 실시간 제거
2,873
Placeholder 포커스시 감추기
2,872
MySQL 중복된 데이터를 삭제
2,871
MySQL 중복 데이터 확인
2,870
sessionStorage.getItem 와 sessionStorage.setItem
2,869
제이쿼리 랜덤으로 배경색 변경
2,868
preg match에 관한 정규식
2,867
Stream an audio file with MediaPlayer 오디오 파일 스트리밍 하기
2,866
Audio Streaming PHP Code
2,865
PHP $ SERVER 환경 변수 정리
2,864
Vimeo (비메오) API 를 사용하여 플레이어 컨트롤하기
2,863
iframe 사용시 하단에 발생하는 공백 제거방법
2,862
아이프레임(iframe) 전체화면 가능하게 하기
목록
뮤직트로트 부산광역시 부산진구 가야동 ㅣ 개인정보취급방침ㅣ모바일버전
Copyright ⓒ musictrot All rights reserved.