Jam's story

[JS] call 로 메소드 호출 본문

WEB/JavaScript

[JS] call 로 메소드 호출

애플쩀 2022. 6. 8. 16:22
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>2022.06.08 15:36:28</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>ex11.html</h3>
ex11.html -call()/apply()

<pre>
[    call()]
다른 객체의 메소드를 call 불러서 처리 
</pre>
<script>
    var person1={
        name:"hong",
        age:20,
      /*   print:function(){
            return this.name+"/"+this.age;
        } */
    };
    var person2={
        name:"admin",
        age:40,
       /*  print: function(){
            return this.name+"/"+this.age;
        } */
    };

    var person={
        //속성
        //속성
        print: function(){
            return this.name+"/"+this.age;
    }}
    
    /*     console.log(person1.print());
    console.log(person2.print());
    function test(){} */
    console.log(person.print.call(person1));
    console.log(person.print.apply(person2));
</script>
</body>
</html>

 

 

 

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>2022.06.08 15:36:28</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h3>ex11.html</h3>
ex11.html -call()/apply()

<pre>
[    call()]
다른 객체의 메소드를 call 불러서 처리 
</pre>
<script>
    var person1={
        name:"hong",
        age:20,
      /*   print:function(){
            return this.name+"/"+this.age;
        } */
    };
    var person2={
        name:"admin",
        age:40,
       /*  print: function(){
            return this.name+"/"+this.age;
        } */
    };

    var person={
        //속성
        //속성
        print: function(city,lang){
            return this.name+"/"+this.age+city+"/"+lang;
    }}
    
    /*     console.log(person1.print());
    console.log(person2.print());
    function test(){} */
    console.log(person.print.call(person1,'seoul','kr')); //나열
    console.log(person.print.apply(person2,['seoul','kr'])); //배열
</script>
</body>
</html>

'WEB > JavaScript' 카테고리의 다른 글

[JS] 스크롤 표시하기  (0) 2022.06.08
[JS] 한문자씩 읽어오기  (0) 2022.06.08
[JS] export  (0) 2022.06.08
[JS] 클래스  (0) 2022.06.08
[JS] 람다식  (0) 2022.06.08
Comments