아 날로 그 구현 call, apply 및 bind
apply. call. bind 는 함수 가 실 행 될 때 문맥 (this 지향) 을 바 꾸 기 위해 존재 합 니 다.
구별:
생각:
코드 이전 판:
      Function.prototype.bind = function(context) {
           let ctx = context || window
           //     this  context
           ctx.func = this
           console.log(this, '------this')
           //     
           let args = Array.from(arguments).slice(1)
           //                  ?
           // const res = args.length ? ctx.func(...args) : ctx.func()
           const res = ctx.func(...args)
           delete ctx.func
           //     ?     OK 
           return res
       }
       let name = '   '
       function sayName() {
           console.log(this.name)
       }
       let obj = {
           name: '       '
       }
       sayName.bind(obj)
apply 의 간단 한 시 뮬 레이 션 실현
apply 의 실현 은 콜 과 같 습 니 다. 전 삼 방식 을 바 꾸 는 것 에 불과 합 니 다.
       Function.prototype.apply = function(context) {
            let ctx = context || window
            ctx.func = this
            let args = arguments[1]
            let isArray = Array.isArray(args)
            if (!isArray) {
                alert('-------          ')
                return
            }
            let res = args ? ctx.func(...args) : ctx.func()
            delete ctx.func
            return res
        }
        let name = '   '
        function sayName() {
            console.log(this.name)
        }
        let obj = {
            name: '       '
        }
        sayName.apply(obj, [12])
bid 의 시 뮬 레이 션 실현
생각:
      Function.prototype.bind = function(context) {
            //         ,        
            let ctx = JSON.parse(JSON.stringify(context)) || window
            ctx.func = this
            let args = Array.from(arguments).slice(1)
            return function() {
                return args.length ? ctx.func(...args) : ctx.func()
            }
        }
        let name = '   '
        function sayName() {
            console.log(this.name)
        }
        let obj = {
            name: '       '
        }
        // sayName.bind(obj)
        // sayName.apply(obj, [12])
        sayName.bind(obj)()
참고 문서
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
전단 자동화 워 크 플 로 의 hooks예 를 들 어 우 리 는 git commt 전에 eslint 코드 검사, npm install 전에 프로젝트 의존 도 를 검사 하고 싶 습 니 다.전형 적 인 상황 에서 각종 도 구 는 특정한 동작 이 발생 할 때 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.