JS 原型继承的几种方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">

    function Person() {
        this.name = '老王';
        this.age = 40;
        
    }
    Person.prototype.showName = function () {
        // alert(this.name);
        alert(this.age);
    };

    function Person1() {
        Person.call(this);
    }
    /*
    ** 方法一 类式继承
    **
    */
    // var F = function () {};
    // F.prototype = Person.prototype;
    // Person1.prototype = new F();
    // Person1.prototype.constructor = Person1;

    /*
    ** 方法二 类式继承2
    **
    */
    // Person1.prototype = Person.prototype;
    // Person1.prototype.constructor = Person1;

    /*
    ** 方法三 拷贝继承
    **
    */
    // extend( Person1.prototype, Person.prototype );
    // function extend( obj1, obj2 ) {
    //     for( var attr in obj2 ){
    //         obj1[attr] = obj2[attr];
    //     }
    // }
    /*
    ** 方法四 原型继承
    **
    */
    var a = {
        age : 1000
    };

    var b = Inherit(a);
    b.age = 24;
    alert(b.age);

    function Inherit(obj) {
        var F = function () {};
        F.prototype = obj;
        return new F();
    }


    // var p1 = new Person1();
    // p1.showName();
    </script>
</body>
</html>

  

原文地址:https://www.cnblogs.com/zsongs/p/5592518.html