JavaScript 23 가지 디자인 모델 의 2 원형 모델

40458 단어 디자인 모드
JavaScript 23 가지 디자인 모델 의 2 원형 모델
  • 개념 과 특징
  • 구조 와 실현
  • 응용 장면
  • 응용 실례
  • 총화
  • 개념 과 특징
    개념: 이미 만 든 인 스 턴 스 를 원형 으로 하고 이 인 스 턴 스 대상 을 복사 하여 원형 과 같 거나 비슷 한 새로운 대상 을 만 듭 니 다.
    특징:
  • 효율 적 이 고 대상 이 만 든 세부 사항 을 알 필요 가 없다.
  • 대상 을 많이 쓰 지 않 고 공간 을 절약 합 니 다.

  • 구조 와 실현
    원형 모드 에 서 는 인 스 턴 스 대상 을 원형 으로 제공 하고 이 원형 을 복제 하 는 방법 을 제공 해 야 합 니 다.이곳 의 복 제 는 또 얕 은 복사 와 깊 은 복사 로 나 뉜 다.자 바스 크 립 트 에 서 는 주로 Object. create 를 통 해 대상 clone 을 실현 합 니 다.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>React App</title>
    </head>
    <body>
    <script>
        function Person(name) {
            this.name = name;
            this.clone = function (param) {
                return Object.create(this,{name:{value:param||name}});
            }
        }
        var obj1 = new Person("jack");
        var obj2 = obj1.clone();
        var obj3 = obj1.clone("rose");
        console.log(obj1);
        console.log(obj2);
        console.log(obj3);
        console.log("obj1==obj2?"+(obj1==obj2));
    </script>
    </body>
    </html>
    

    응용 장면
  • 대상 이 같 거나 비슷 하 다.
  • 대상 의 생 성 과정 은 비교적 번 거 롭 지만 복 제 는 비교적 간단 하 다. 예 를 들 어 눈송이 장면 을 만 들 려 면 눈 송 이 를 만 드 는 것 이 비교적 복잡 하고 큰 눈송이 가 직접 복사 하면 된다.

  • 응용 실례
    가상 DOM 을 실현 하여 눈 송 이 를 대량으로 제조 하 다.가상 DOM 생 성 과정 을 간단히 말씀 드 리 겠 습 니 다.
  • 매개 변수 에 따라 new 방법 으로 트 리 구 조 를 만 드 는 요소 대상 을 재 귀적 으로 말한다.
  • 요소 대상 의 type 값 에 따라 텍스트 요소 에 속 하 는 지 일반적인 DOM 요소 에 속 하 는 지 판단 한 다음 에 각각 createElement 구조 함수.
  • 가상 DOM 노드 를 new 방법 으로 연결 합 니 다.
  • 노드 를 루트 요소 에 마 운 트 합 니 다.

  • 다음 사례 에서 원형 모델 을 사용 하 는 곳 이 두 번 째 단계 다.구조 함수 에 mountComponent 방법 을 추가 하 였 다.그래서 눈꽃 을 대량으로 만 들 때 가상 DOM 대상 을 대량으로 만 들 지 않 습 니 다.직접 clone 방법 을 통 해 이 루어 지고 서로 다른 스타일 로 들 어가 전체 화면 크기 가 다 르 고 위치 가 다른 눈꽃 효 과 를 실현 한다.
        //   DOM   
        function ReactDOMComponent(element) {
            //      element    
            this._currentElement = element;
            this._rootNodeID = null;
            //          
            this.clone = function (style) {
                //1.       。
                var str = JSON.stringify(this);
                var newObj = JSON.parse(str);
                //2.      this,     prototype     。
                newObj.__proto__ = this;
                if(style){
                    newObj._currentElement.props.style = style;
                }
               return  newObj;
            }
        }
    
      //             
        var componentInstance = instantiateReactComponent(element) //  vDom  Component
        //      
        var html = componentInstance.mountComponent(0);
        //                 
        for(var i=0;i<100;i++){
            var el= componentInstance.clone(
                "left:"+parseInt(Math.random() * window.innerWidth)+"px;"+
                "top:"+parseInt(Math.random() * (window.innerHeight-0))+"px;"+
                "font-size:"+parseInt(Math.random() * (50))+"px"
            );
            var markup1 = el.mountComponent(0);
            html+=markup1;
        }
        root.innerHTML = html;
    

    전체 코드:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>React App</title>
    </head>
    <style>
        .snow{
            color:#fff;
            position: absolute;
            opacity: 0.9;
        }
    </style>
    <body style="background: black">
    <div id="root"></div>
    <script>
        //       DOM   
        function createElement(type, config, children) {
            var props = {};
            var propName;
            config = config || {};
            var key = config.key || null;
            for (propName in config) {
                if (config.hasOwnProperty(propName) && propName !== "key") {
                    props[propName] = config[propName];
                }
            }
            var childrenLength = arguments.length - 2;
            if (childrenLength === 1) {
                props.children = Array.isArray(children) ? children : [children];
            } else if (childrenLength > 1) {
                var childArray = [];
                for (var i = 0; i < childrenLength; i++) {
                    childArray[i] = arguments[i + 2];
                }
                props.children = childArray;
            }
            return new ReactElement(type, key, props);
        }
        function ReactElement(type, key, props) {
            this.type = type;
            this.key = key;
            this.props = props;
        }
        //      
        function ReactDOMTextComponent(text) {
            //         
            this._currentElement = "" + text;
        }
        //      
        ReactDOMTextComponent.prototype.mountComponent = function() {
            return this._currentElement;
        };
        //   DOM   
        function ReactDOMComponent(element) {
            //      element    
            this._currentElement = element;
            this._rootNodeID = null;
            //          
            this.clone = function (style) {
                //1.       。
                var str = JSON.stringify(this);
                var newObj = JSON.parse(str);
                //2.      this,     prototype     。
                newObj.__proto__ = this;
                if(style){
                    newObj._currentElement.props.style = style;
                }
               return  newObj;
            }
        }
        //   DOM   
        ReactDOMComponent.prototype.mountComponent = function() {
            var props = this._currentElement.props;
            //     
            var tagOpen = " + this._currentElement.type;
            var tagClose = "" + this._currentElement.type + ">";
            //       
            for (var propKey in props) {
                if (props[propKey] && propKey != "children" && !/^on[A-Za-z]/.test(propKey)) {
                    tagOpen += " " + propKey + "=" + props[propKey];
                }
            }
            //      dom
            var content = "";
            var children = props && props.children || [];
            var childrenInstances = []; //      component   
            children.forEach((child, key) => {
                var childComponentInstance = instantiateReactComponent(child);
                //         
                childComponentInstance._mountIndex = key;
                childrenInstances.push(childComponentInstance);
                //           
                var childMarkup = childComponentInstance.mountComponent();
                //      
                content += " " + childMarkup;
            });
            //   component   
            this._renderedChildren = childrenInstances;
            //     html  
            return tagOpen + ">" + content + tagClose;
        };
        //     
        function instantiateReactComponent(node) {
            //       
            if (typeof node === "string" || typeof node === "number") {
                return new ReactDOMTextComponent(node);
            }
            //          
            if (typeof node === "object" && typeof node.type === "string") {
                //    ,       component
                return new ReactDOMComponent(node);
            }
        }
        //      
        var element = createElement(
            'div',
            {class:'snow'},
            '❆'
        );
        //             
        var componentInstance = instantiateReactComponent(element) //  vDom  Component
        //      
        var html = componentInstance.mountComponent(0);
        //                 
        for(var i=0;i<100;i++){
            var at = componentInstance.clone(
                "left:"+parseInt(Math.random() * window.innerWidth)+"px;"+
                "top:"+parseInt(Math.random() * (window.innerHeight-0))+"px;"+
                "font-size:"+parseInt(Math.random() * (50))+"px"
            );
            var markup1 = at.mountComponent(0);
            html+=markup1;
        }
        root.innerHTML = html;
    </script>
    </body>
    </html>
    

    총결산
    상기 사례 에서 원형 모델 을 실현 하 는 두 가지 관건 적 인 절차.
  • JSON. stringify 와 JSON. parse 를 통 해 대상 의 깊이 있 는 복 제 를 실현 합 니 다.
  • 대상 을 바 꾸 는 new 을 통 해 계승 을 실현 한다 (원형 상의 속성 과 방법 을 사용 할 수 있다).
  • 좋은 웹페이지 즐겨찾기