美文网首页
Es5 继承

Es5 继承

作者: _cxrs_ | 来源:发表于2020-03-29 20:22 被阅读0次

Es5 对象和原型链实现混合继承

方法的区别

在构造函数和原型链添加方法区别:


Object.prototype.test=function(){

            alert('我是原型链上 test()');

        }

            function Person(){

                this.name='张三';

                this.age=20;

                function test(){

                    alert('我是Person上 test()')

                }

            }

            function Son(){



            }

            var p=new Son()

            p.test();

            //  打印的是原型链上 test()

结论: 原型链上的方法会被多个实例 共享,构造函数不会

静态方法:


function static(){

            }

            static.add=function(){

                alert('静态方法')

            }

E5的继承

原理: 原型链+对象冒充的组合继承模式

对象冒充实现继承


function Father(){

}

function Son(){

}function Father(){

          this.name='张三';

              this.age=20;

              this.test =function(){

                  alert('我是Father')

              }

}

function Son(){

              Father.call(this);  // 通过改变 this 指向 对象冒充继承

          }

          var w=new Son();

          w.test();

总结: 对象冒充可以继承构造的数里面的属性和方法 但是无法继承原型链上的属性和方法

原型链实现继承


        function Father(name,age){

            this.name='张三';

                this.age=20;

                this.test =function(){

                    alert('我是Father')

                }

  }

function Son(){

                Father.call(this);  // 通过改变 this 指向 对象冒充继承

            }

            Father.prototype.wx=function(){

                alert('原型链上的方法')

            }

            Father.prototype.sex='男'

            Son.prototype=new Father()

            var w=new Son();

            w.wx();



**总结** 原型链实现继承:可以继示构造数里面的属性和方法也可以继承原型链上面的属性和方法 但是实例化子类时没办法给父类传参

优化



    function Father(name, age) {

            this.name = name;

            this.age = age;

            this.test = function () {

                alert(`我叫${name} 今年${age}`)

            }

        }

        function Son(name,age) {

            Father.call(this, name, age); // 通过改变 this 指向 对象冒充继承

        }

        Father.prototype.wx = function () {

            alert('原型链上的方法')

        }

        Father.prototype.sex = '男'

        Son.prototype = new Father()

        var w = new Son('李白',20);

        w.test()

相关文章

网友评论

      本文标题:Es5 继承

      本文链接:https://www.haomeiwen.com/subject/bgzuuhtx.html