实用JS系列——面向对象中的类和继承

背景:

       在最开始学习JavaScript时,我们就知道,它是一种脚本语言,也有面向对象机制。但它的面向对象继承机制是基于原型的,即Prototype。今天,我们就来找一下JSOO的影子。

 

创建类

1、用function模拟创建类,类似构造函数


        function Animal() {
            this.name = "动物";
            this.action = "打招呼";
        }
        var animal = new Animal();
        alert(animal.name + ":" + animal.action);

也可以在定义时加上参数。

      function Animal(name,action) {
            this.name = name;
            this.action = action;
        }
        var animal = new Animal("小动物", "打招呼");
        alert(animal.name+":"+animal.action);


两种方式显示结果如下:

2、用prototype对象

        function Animal() { };
        Animal.prototype.name = "小动物";
        Animal.prototype.action = "打招呼";
        Animal.sayHello = function () {
            alert(this.name+"你好");
        }


       在上述两种方式中,我们创建了Animal的类,并且new出了它的对象animal。其中,name和action两个属性,sayHello为方法。在 function 中用 this 引用当前对象,通过对属性的赋值来声明属性。如果用var声明变量,则该变量为局部变量,只允许在类定义中调用。


继承

       javascript支持实现继承,不支持接口继承。继承主要是通过原型链来实现的。
       在js中,每一个构造函数都有一个prototype对象,每一个对象的实例都有一个__proto__指针指向其构造函数的prototype对象。

       同样,先看用prototype

       //Animal类
        var Animal = function (name,action) {
            this.name = name;
            this.action = action;

        }

        //Animal的方法
        Animal.prototype.sayHello = function () {
            alert(this.name + "say hello");
        }

        var animal = new Animal("小猫", "问好");
        animal.sayHello();

        //Cat类 
        function Cat() { }
        Cat.prototype = new Animal("小猫", "你好");
        var cat = new Cat();
        Cat.prototype.flur = "black";
        cat.sayHello();



通过构造函数方式,实现继承关系。

       //构造函数
        function Animal(name,action) {
            this.name = name;
            this.action = action;
            this.sayHello = function () {
                alert(this.name + "say hello");
            }
        }

        function Cat(name, action) {
            this.tempMethod = Animal;
            this.tempMethod(name);
            this.action = action;

        }

        var animal = new Animal("动物","问好");
        animal.sayHello();
        var cat = new Cat("小猫", "你好");
        cat.sayHello();

总结:

       在JS中,创建类和实现继承的方法还有很多种,有兴趣可以自己查阅学习,这里说的两种方式,我认为是比较容易理解的。

       面向对象的JavaScript使得编程更加简洁易懂,增强了可维护性,适合编写富客户端程序。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值