JavaScript OOP

2015-01-09 12:15  2631人阅读  评论 (0)

简单说明

常见的面向对象是子类继承父类,但是javascript是子类继承父类的实例对象,也就是原型,这点要搞清楚.

常见面向对象的继承

父类     -> 子类
 |           |
父类对象 -> 子类对象

javascript的继承

父类
 |
父类对象 -> 子类
             |
            子类对象

JavaScript OOP演示代码

下面的代码演示了了继承,调用父类构造函数,调用父类方法.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript OOP</title>
    <script type="text/javascript">
    function A(name) {
        this.a = name;
    }
    A.prototype.a = "AA";
    A.prototype.hello = function(msg) {
        console.log(this.a + ": " + msg);
    };

    function B(name) {
        A.call(this, 'aa'); // 调用父类构造函数
        this.b = name;
    }
    B.prototype = new A('aaa'); // 继承父类的对象 这里是对象不是类
    B.prototype.constructor = B; // 恢复构造函数
    B.prototype.b = "BB";
    B.prototype.hello = function(msg) {
        B.prototype.hello.call(this, msg); // 调用父类方法
        console.log(this.b + ": " + msg);
    };

    function C(name) {
        B.call(this, 'bb'); // 调用父类构造函数
        // C.prototype.constructor.call(this, 'bb'); // 也可以
        this.c = name;
    }
    C.prototype = new B('bbb'); // 继承父类的对象 这里是对象不是类
    C.prototype.constructor = C; // 恢复构造函数
    C.prototype.c = "CC";
    C.prototype.hello = function(msg) {
        B.prototype.hello.call(this, msg); // 调用父类方法
        console.log(this.c + ": " + msg);
    };

    // 创建对象
    var a = new A('aa');
    var b = new B('bb');
    var c = new C('cc');

    // 构造函数
    console.log(a.constructor, b.constructor, c.constructor);
    // 类名
    console.log(a.constructor.name, b.constructor.name, c.constructor.name);
    // 继承
    console.log(c instanceof C, c instanceof B, c instanceof A);

    // 调用方法
    c.hello("dotcoo.com");
    </script>
</head>
<body>

</body>
</html>

参考网址

http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html





豫ICP备09035262号-1