javascript call () 과 apply ()

2952 단어 JavaScript
ECMAScript 는 Function 원형 에 두 가지 방법 을 정 의 했 는데 하 나 는 call () 과 apply () 이다.이 두 가지 방법 을 사용 하면 다른 대상 의 방법 처럼 함 수 를 호출 할 수 있다.대상 을 데이터 와 같은 매개 변수 로 함수 에 전달 하고 매개 변 수 는 함 수 를 호출 합 니 다.
그의 두 가지 차 이 는 콜 의 첫 번 째 매개 변 수 는 반드시 대상 (또는 함수) 이 어야 하고 나머지 매개 변 수 는 임의로 할 수 있다 는 것 이다.한편, apply 는 보통 두 개의 매개 변수 만 있 고 첫 번 째 는 대상 이나 함수 이 어야 하 며 두 번 째 는 아래 표 시 된 집합 이다.
예 를 들 면:
function dow(s){
    document.write("<h1>"+s+"</h1>");
}

function Point(x,y){
    this.x=x;
    this.y=y;
    
    this.toString=function(){
        return "("+[x,y]+")";
    }
}

function Vectory(x,y){
    this.x=x;
    this.y=y;
    
    this.toString=function(){
        return "("+[x,y]+")";
    }
}

function add(x,y){
    return new this.constructor(this.x+x,this.y+y);
}

var p=new Point(2,4);//       
var v=new Vectory(3,5);
//call()       call          call     ,  call                      ,   call      


dow(p);
dow(add.call(p,3,5));//      p       add
dow(add.apply(p,[2,6]));//        ,               



.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

좋은 웹페이지 즐겨찾기