码迷,mamicode.com
首页 > Web开发 > 详细

关于 JS 面向对象继承属性和方法的小例子

时间:2015-02-08 19:18:59      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>关于 JS 面向对象继承属性和方法的小例子</h1>
</body>
</html>
<script>

    //人的构造函数
    function PeopleClass()
    {
        this.type = ‘人‘;
    }    
    //人所拥有的方法
    PeopleClass.prototype = {
        getType:function()
        {
            console.log(‘这是一个人‘);
        },
        getSex:function()
        {
            console.log(‘我是男的‘);
        }
    };
    //学生的构造函数
    function StudentClass( name , sex )
    {
        //继承 PeopleClass 的所有属性
        PeopleClass.apply( this , arguments );
        //继承 PeopleClass 的所有方法
        for( var prop in PeopleClass.prototype )
        {
            //this 指向的是 PeopleClass
            var proto = this.constructor.prototype;
            if ( !proto[prop] ) {
                proto[prop] = PeopleClass.prototype[prop];
            }
            proto[prop][‘super‘] = PeopleClass.prototype;
        }

        this.name = name;
        this.sex = sex;
    }

    var stu = new StudentClass(‘Zion‘,‘男‘);
    console.log(stu.type); //
    stu.getType();    //这是一个人
    stu.getSex(); //我是男的

</script>

 

关于 JS 面向对象继承属性和方法的小例子

标签:

原文地址:http://www.cnblogs.com/zion0707/p/4280265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!