首页 > Web开发 > 详细

JS 原型继承的几种方法

时间:2016-06-17 00:34:30      阅读:303      评论:0      收藏:0      [点我收藏+]
<!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>

  

JS 原型继承的几种方法

原文:http://www.cnblogs.com/zsongs/p/5592518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!