>  기사  >  웹 프론트엔드  >  JS의 객체지향에서 상속받은 작은 것들(인스턴스)

JS의 객체지향에서 상속받은 작은 것들(인스턴스)

青灯夜游
青灯夜游원래의
2018-09-15 16:17:081033검색

이 장에서는 JS 객체지향 상속의 작은 것(인스턴스)을 소개하여 JS 상속의 특징이 무엇인지 이해할 수 있도록 하겠습니다. 객체 지향의 상속에 대한 약간의 지식. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

JS의 상속 기능:

1. 🎜🎜#2. 하위 클래스는 상위 클래스의 메서드와 속성을 사용할 수 있습니다

3. 하위 클래스를 변경해도 상위 클래스에는 영향을 주지 않습니다

다음은 설명을 위한 예입니다. JS 상속

이 코드는 상위 클래스와 해당 프로토타입을 생성하고 하위 클래스도 생성하며 상위 클래스의 개인 속성을 상속합니다.

<script>
        //这是父类
        function Father(name,age,marry){
            this.name=name;
            this.age=age;
            this.marry=marry;
        }
        //父类的原型
        Father.prototype.showName=function(){
            alert(this.name);
        }

        //子类
        function Son(name,age,marry,weight){
            Father.call(this,name,age,marry);
            this.weight=weight;
        }
        
 </script>

자식이 필요할 때 Son이 원할 때 상위 클래스의 프로토타입을 상속받기 위해 처음에 이렇게 했습니다

<script>
        //这是父类
        function Father(name,age,marry){
            this.name=name;
            this.age=age;
            this.marry=marry;
        }
        //父类的原型
        Father.prototype.showName=function(){
            alert(this.name);
        }

        //子类
        function Son(name,age,marry,weight){
            Father.call(this,name,age,marry);
            this.weight=weight;
        }
        
        //错误的做法
        Son.prototype=Father.prototype;
        Son.prototype.showAge=function(){
            alert(this.age);
        }
        var father=new Father(&#39;王大锤&#39;,30,true);
        alert(father.showAge);
        
</script>

JS의 객체지향에서 상속받은 작은 것들(인스턴스)실행 결과를 보면 하위 클래스의 프로토타입이 변경 사항은 상위 클래스의 프로토타입에 영향을 미치며, 상위 클래스의 프로토타입에는 상속의 세 번째 특성을 위반하는 showAge 메서드가 없습니다.

분석 이유: 위 코드의 20번째 줄 Son.prototype=Father.prototype; 여기서 '='는 양쪽의 객체이므로 참조인 경우 해당 의미입니다. 왼쪽에 하나 물체가 변하면 반드시 오른쪽에 있는 물체에도 영향을 미칠 것입니다. 이것이 하위 클래스의 프로토타입에 대한 변경 사항이 상위 클래스의 프로토타입에 영향을 미치는 이유입니다.

Solution

방법 1: 핵심 아이디어, 이전 문제는 '='가 문제를 일으키는 참조 관계가 아니라는 것입니다. '='는 항상 참조가 아닌 할당 관계임을 보장합니다. 여기서는 상위 클래스 객체를 하위 클래스에 복사하는 Clone() 메서드를 정의합니다.

Clone() 메서드에서 재귀를 사용하는 이유는 복사 과정에서 객체가 객체 내에 중첩될 수 있기 때문입니다.

<script>
        //这是父类
        function Father(name,age,marry){
            this.name=name;
            this.age=age;
            this.marry=marry;
        }
        //父类的原型
        Father.prototype.showName=function(){
            alert(this.name);
        }

        //子类
        function Son(name,age,marry,weight){
            Father.call(this,name,age,marry);
            this.weight=weight;
        }
        Son.prototype=new Clone(Father.prototype);
        Son.prototype.showAge=function(){
            alert(this.age);
        }
        var father=new Father(&#39;王大锤&#39;,30,true);
        alert(father.showAge);

        //通过克隆对象:核心思路是保证 &#39;=&#39; 是赋值的关系,而不是引用,也就是保证 &#39;=&#39; 的右边不是对象
        function Clone(obj){
            for(var i=0;i<obj.length;i++){
                if(typeof(obj[key]==&#39;object&#39;)){
                    this.key=new Clone(obj[key]);
                }else{
                    this.key=obj[key];
                }
            }
        }  
</script>

JS의 객체지향에서 상속받은 작은 것들(인스턴스)방법 2: 코드는 매우 간단하지만 생각하기 어렵고 첫 번째 방법만큼 이해하기 쉽지 않습니다. 핵심 아이디어: 객체 자체의 속성 변경은 해당 생성자의 속성 변경에 영향을 미치지 않습니다.

<script>
        //这是父类
        function Father(name,age,marry){
            this.name=name;
            this.age=age;
            this.marry=marry;
        }
        //父类的原型
        Father.prototype.showName=function(){
            alert(this.name);
        }

        //子类
        function Son(name,age,marry,weight){
            Father.call(this,name,age,marry);
            this.weight=weight;
        }
        function fn(){}
        fn.prototype=Father.prototype;
        Son.prototype=new fn();      
        Son.prototype.showAge=function(){
            alert(this.age);
        }
        var father=new Father(&#39;王大锤&#39;,30,true);
        alert(father.showAge);

        //通过克隆对象:核心思路是保证 &#39;=&#39; 是赋值的关系,而不是引用,也就是保证 &#39;=&#39; 的右边不是对象
        // Son.prototype=new Clone(Father.prototype);
        // function Clone(obj){
        //     for(var i=0;i<obj.length;i++){
        //         if(typeof(obj[key]==&#39;object&#39;)){
        //             this.key=new Clone(obj[key]);
        //         }else{
        //             this.key=obj[key];
        //         }
        //     }
        // }  
</script>

위 내용은 JS의 객체지향에서 상속받은 작은 것들(인스턴스)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.