call () 실현 원리 (function 원형상의 방법)

/span>html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>call() title>
head>
<body>

body>
html>
<script type="text/javascript">
    // . 
    Function.prototype.call=function () {
        //this: call 
        //call this, call 
        //  this 
        // ,null,undefined, this()
        var ary=[...arguments].slice(1);
        if(arguments[0]==undefined){
            this(...ary);
            //eval("this("+ary+")");
        }else {
            // 
            var obj=Object(arguments[0]);// 

            obj.__proto__.fn=this;
            obj.fn(...ary);
            delete obj.__proto__.fn;
        }

    };
    function fn(n) {
        console.log(n);
        console.log(this);
    }
    function fn1() {
        console.log(" fn1");
    }
    var o={a:1};
    fn.call(o,1);
script>
<script>

   Function.prototype.call=function () {
       var ary=[...arguments].slice(1);
       if(arguments[0]==undefined){
         this(...ary);
       }else {
           var obj=Object(arguments[0]);
           obj.__proto__.fn=this;
           obj.fn(...ary);
           delete obj.__proto__.fn;
       }
       return this;
   };
    var obj={b:1};
   function ff(x) {
       console.log(this);
   };
   console.log(ff.call(obj, 1, 2).name);
script>

좋은 웹페이지 즐겨찾기