의 JavaScript 고급 기술, 고급 함수 (1)

10204 단어
목차
  • 1. 고급 함수
  • 1 - 1 안전 한 유형 검사
  • 1 - 2 작용 역 안전 의 구조 함수
  • 1 - 3 타성 불 러 오기 함수
  • 1 - 4 함수 귀속
  • 1 - 5 함수 코 리 화
  • 1 - 6 반 함수 코 리 화

  • 고급 함수
    1 - 1 안전 한 유형 검사
    유형 검 사 를 생각하면 머 릿 속 의 첫 번 째 반응 은 자 바스 크 립 트 의 세계 에서 도대체 어떤 유형 이 있 는 지 (이것 은 정말 오래된 문제 이다)
           2  :            
    
               : string、number、bool、undefined、null
    
               : Array、Function、Object

    그러면 type 과 instanceof 로 이 몇 가지 데이터 형식 으로 되 돌아 오 는 내용 을 각각 살 펴 보 겠 습 니 다. 왜 type 과 instanceof 를 이용 하 는 것 이 안전 하지 않 은 유형 검 측 이 라 고 말 합 니까?
    const str = 'test'
    const num = 12
    const bool = false
    const unde = undefined
    const nulls = null
    const Array = [1,2,3,4]
    const Object = {name: 'zzz'}
    
    const checkType = (type) => {
        return typeof(type)
    }
    
    //    type    
    console.log(checkType(str))         // string
    console.log(checkType(num))         // number
    console.log(checkType(bool))        // boolean
    console.log(checkType(unde))        // undefined
    console.log(checkType(nulls))       // object
    console.log(checkType(Array))       // object
    console.log(checkType(Object))      // object
    //     null、Array、Object       object      ( bug   )
    
    //   instanceof    
    
    const checkInstance = (type) => {
        return type instanceof String
    }
    
    console.log(checkInstance(str)) //   false       ?
    
    //             instanceof     。
    

    1 - 1 - 1 instanceof 의 원리
    instanceof 의 기능 실현 은 전자 가 후자 인지 아 닌 지 의 실례 이 고 구체 적 인 코드 는 다음 과 같다. eg:
    
    let res = a instanceof A
    
    // a   A     
    // A   a      
    //    a   __proto__  == A   prototype     a instanceof A  == true       false

    그 중 몇 가지 관건 적 인 점 은 다음 과 같다.
  • constrcutor, proto, prototype, 원형 대상 이라는 네 가지 점 에 대한 이해.
  • 좋 은 글 추천 해 주세요. prototype, proto, constructor 의 삼각관계
  • 위로 돌아 가기 a.proto__ 가리 키 는 것 은 a 의 원형 대상
  • 이다.
  • A. prototype 은 인 스 턴 스 대상 의 원형 대상
  • 을 가리킨다.
    var Foo = function() {
        this.setName = (name) => {
            this.name = name
        }
    }
    
    var foo = new Foo
    
    Foo.prototype     =>     (       )
    //                           。             
    
    Foo.prototype.constructor     =>       (Foo)
    
    foo.__proto__     =>     (       )
    
    foo.constructor    =>      (Foo)

    1 - 2 역할 영역 안전 한 구조 함수
    전역 역할 영역 에서 함수 구조 함 수 를 호출 합 니 다. new 를 사용 하지 않 았 기 때문에 전역 역할 영역 에 불필요 한 속성 을 추가 합 니 다.
    
    function Person(name,job) {
        this.name = name
        this.job = job
    }
    
    //       New   
    
    var person = Person('zhangsan','sell') 
    
    console.log(window.name, window.job)    // zhangsan sell
    console.log(person.name, person.job)    // VM76:11 Uncaught TypeErrorr

    이 문 제 는 this 대상 의 늦 은 귀속 으로 인 한 것 이기 때문에 함수 에서 확인 해 야 합 니 다 this .
    function Person(name){
        if(this instanceof Person){
            this.name = 'zhang';
        } else {
            return new Person(name)
        }
    }
    
    var person = Person('zhang')
    console.log(window.name)    //  ''
    console.log(person.name)    //  zhang

    1 - 3 타성 불 러 오기 함수
    불활성 불 러 오기 함수 가 실 행 된 가 지 는 함수 가 처음 호출 될 때 실 행 됩 니 다. 첫 번 째 호출 과정 에서 이 함 수 는 다른 적당 한 방식 으로 실 행 된 함수 로 덮어 씁 니 다. 그러면 원 함수 에 대한 호출 은 더 이상 실 행 된 가 지 를 통 해 판단 하지 않 아 도 됩 니 다.(절 약 력)
    1 - 3 - 1 응용 장면
    1. AJAX 는 서로 다른 브 라 우 저 에서 호환성 2, 앱 에 H5 를 내장 하여 서로 다른 환경 에서 같은 기능 방법 으로 쓰 는 방법 이 다 릅 니 다. 3. H5 는 서로 다른 플랫폼 에서 여러 가지 표현 형식 이 하나의 방법 으로 나타 나 는 것 이 다 릅 니 다.
    1 - 3 - 2 주의 하 는 곳.
    1. 응용 이 빈번 할 수록 이런 모델 의 장점 을 나 타 낼 수 있다.
    1-3-3 Demo
    
    const getCurEnv = () => {
        //       chrome      
        return window.navigator.userAgent.toLowerCase().match(/chrome/i) !== null
    }
    
    const Person = function(name) {
        this.name = name
    }
    
    const http = {
        created: function() {
            if (getCurEnv()) {
                console.log(this)
                this.created = function() {
                    console.log('test1')
                    return new Person('zhang1')
                }
                console.log('test2')
                return new Person('zhang2')
            } else {
                this.created = function() {
                    console.log('test3')
                    return new Person('zhang3')
                }
            }
        },
        Atest: ()=> {
            console.log(this)    // window {}
        },
        Ftest: function() {
            console.log(this)    // http {}
        }
    }
    
    http.created()  // test2 Person {name: "zhang2"}
    http.created()  // test1 Person {name: "zhang1"}
    
    //                                  。               。

    1 - 4 함수 귀속
    이 기 교 는 함 수 를 변수 로 전달 하 는 동시에 코드 실행 환경 을 유지 하기 위해 리 셋 함수 와 이벤트 처리 와 함께 자주 사용 합 니 다.
    많은 자 바스 크 립 트 라 이브 러 리 는 함 수 를 지정 한 환경 에 연결 할 수 있 는 함 수 를 실 현 했 는데 이 함 수 는 일반적으로 bind () 라 고 부른다.간단 한 bind () 함수 가 함수 와 환경 을 받 아들 이 고 주어진 환경 에서 주어진 함 수 를 호출 하 는 함 수 를 되 돌려 주 며 모든 매개 변 수 를 그대로 전달 합 니 다.이 함 수 는 닫 힌 가방 을 되 돌려 줍 니 다.
    위의 언어 설명 은 항상 허무맹랑 하 다. 우 리 는 직접 Demo 에 올 라 간다.
    1-4-1 Demo
    
    var obj1 = {
        name: 'zhang',
        getName: function() {
            console.log(arguments[0][2], 'obj1')
            return this.name
        }
    }
    
    var obj2 = {
        name: 'lisi',
        getName: function() {
            console.log(arguments, 'obj2')
            return this.name
        }
    }
    
    function Bind(fn, context) {
        return fn.call(context, arguments)
    }
    
    Bind(obj1.getName,obj2,'xxxxx') 
    
    // Arguments [Arguments(3), callee: ƒ, Symbol(Symbol.iterator): ƒ] "obj1"
    // 'lisi'
    //        arguments                ,            
    // arguments      。

    1-4-2 arguments
    클래스 배열 (Array - like)
  • 아래 표 시 를 통 해 각 요소 에 접근 할 수 있 습 니 다
  • length 속성
  • arguments 의 데이터 형식 은 object
  • 입 니 다.
  • for 와 for - in 방법 사용 가능
  • Array 원생 방법 미 비
  • Demo
    
    var test = function() {
        console.log(arguments)
        console.log(arguments[0])
        console.log(arguments.length)
        console.log(typeof arguments)
        for(var i = 0; i

    클래스 배열 을 배열 로 변환 합 니 다.
  • 방법 1:
  • var test = function() {
        console.log(arguments)
        var arrArg = Array.prototype.slice.call(arguments)
        console.log(arrArg)
    }
    
    test(1,2,3,4) // [1, 2, 3, 4]
  • 방법 2:
  • var test = function() {
        console.log(arguments)
        var arrArg = Array.from(arguments)
        console.log(arrArg)
    }
    
    test(1,2,3,4) // [1, 2, 3, 4]

    1 - 4 - 3 ES5 중 원생 bind () 방법 상세 설명
    문자 해석 이 힘 들 면 쇼 코드 ~ 데모:
    var obj = {
        a: 1,
        b: 2,
        getCount: function(c, d) {
            return this.a + this.b + c + d
        }
    }
    console.log(obj.getCount(3,4))  // 10
    window.a = window.b = 0
    var funcs = obj.getCount
    funcs(3,4)                      // 7
    

    bind 는 function 의 함수 확장 방법 입 니 다. bind 이후 코드 는 func 내부 의 this 지향 (obj) 호 환 IE9 + Demo 를 다시 연결 합 니 다.
    var obj = {
        a: 1,
        b: 2,
        getCount: function(c, d) {
            return this.a + this.b + c + d
        }
    }
    console.log(obj.getCount(3,4))  // 10
    window.a = window.b = 100
    var funcs = obj.getCount.bind(obj)
    funcs(3,4)          // 10
    // var funcs = obj.getCount.bind(window)
    // funcs(3,4)       // 207

    1 - 5 함수 코 리 화
    부분 구 치 라 고도 부른다.커 리 화 는 그 자체 가 예상 할 수 있 는 매개 변 수 를 고정 시 키 고 특정한 함수 로 돌아 가 특정한 수 요 를 처리 하 는 것 이다.이것 은 함수 의 적용 성 을 증가 시 켰 으 나 함수 의 적용 범 위 를 낮 추 었 다.문자 의 정 의 는 시종 받 아들 이기 어 려 우 니 쇼 코드 를 사용 하 세 요 Demo: 기장 도 구 를 작성 한 다음 에 매일 데 이 터 를 기록 하고 마지막 으로 일주일 동안 의 데 이 터 를 통계 하 세 요.how ?
    let weekCost = 0
    const cost = function(num) {
        weekCost += num 
    }
    cost(100)   // 100
    cost(200)   // 300
    cost(300)   // 600
                   ,         ,                ,          。                 。
    const currying = function(fn) {
        let args = []
        return function() {
            if (arguments.length == 0) {
                return fn.apply(this, args)
            } else {
                let test = [].push.apply(args,arguments)
                // return fn.call(this, arguments)
            }
        }
    }
    
    const costs = (function() {
        let money = 0
        return function() {
            money = 0
            for(let i = 0; i

    소결 1:
        dmeo  ,    cost()  ,        ,               ,           ,    cost()           。                cost()  ,            ,        。               。                        ? 
    
         ,           !

    Demo
    const currying = function(fn) {
        let args = Array.prototype.slice.call(arguments, 1)
        return function() {
            let innerArgs = Array.prototype.slice.call(arguments)
            return fn.apply(this, args.concat(innerArgs))
        }
    }
    
    const add = function(n, m) {
        return n + m
    }
    
    var curriedAdd = currying(add, 3)
    
    console.log(curriedAdd(5)) // 8
    

    소결 2:
         ,                        。
              ,      。

    주의 하 다.
    코 리 화 함수 든 바 인 딩 함수 든 추가 비용 을 가 져 올 수 있 으 므 로 남용 해 서 는 안 된다.
    1 - 6 반 함수 코 리 화
    반면 반 코 리 화 작용 은 함수 의 적용 성 을 확대 하여 원래 특정 대상 으로 가지 고 있 던 기능 의 함 수 를 임 의 대상 에 게 사용 할 수 있 게 한다.
    핵심:
    uncurrying 함 수 를 통 해 원래 한 대상 에 만 사용 할 수 있 는 방법 을 말 하고 더 많은 대상 으로 확장 하여 참조 할 수 있 습 니 다.showCode:
    
    Function.prototype.uncurrying = function() {
        var that = this;
        return function() {
            return Function.prototype.call.apply(that, arguments);
        }
    }
    
    const test1 = {}
    const test2 = {}
     
    test1.sayHi = function () {
        return "Hello " + this.value +" "+[].slice.call(arguments);
    }
    
    test2.sayHiuncurrying = test1.sayHi.uncurrying()
    
    console.log(test2.sayHiuncurrying({value:'world'},"hahaha"));
    
    // Hello world hahaha

    핵심 코드 가 보 여 졌 습 니 다. 자세히 읽 어보 세 요 ~
    자, 오늘 은 여기까지 쓰 고 데모 에 대한 설명 을 계속 보완 하 겠 습 니 다. 모 르 는 것 은 댓 글로 토론 하 셔 도 됩 니 다 ~
    GitHub 주소: (환영 스타, 환영 추천:)
    전단 고급 기술, 고급 함수 (1)

    좋은 웹페이지 즐겨찾기