美文网首页
【管子先生的Node之旅·3】JavaScript基础复习(三)

【管子先生的Node之旅·3】JavaScript基础复习(三)

作者: 管子先生 | 来源:发表于2017-10-27 15:09 被阅读0次

    JavaScript (es5) 没有 class 关键字。类只能通过函数来定义:

        // 定义一个动物类
        function Animal() {}
    

    Animal 的实例定义函数,可以通过prototype属性来定义:

        // 定义eat函数
        Animal.prototype.eat = function(foot) {}
    

    此时 this 指向的不是 global 对象,而是通过该类创建的实例对象:

        // 定义一个 Animal 类
        function Animal(name) {
            this.animalName = name;
        }
    
        // 定义 eat 函数
        Animal.prototype.eat = function(foot) {
            return this.animalName + '正在吃' + foot;
        }
    
        var animal = new Animal('狗狗');
        animal.eat('狗粮'); //=>狗狗正在吃狗粮
    

    继承

    JavaScript 有基于原型的集成特点。通常来说你可以通过如下方法来模拟继承:

        // 定义一个要继承 Animal 的构造器
        function dog() {}
    
        // 通过 prototype 来实现继承
        dog.prototype = new Animal('狗狗');
    

    随后,就可以为子类定义属性和方法:

        // 定义 fear 函数
        Dog.prototype.fear = function(name) {
            return this.animalName + '害怕' + name;
        }
    
        var dog = new Dog();
        dog.fear('小奶猫'); //=>狗狗害怕小奶猫
    

    还可以通过 prototype 来重写和调用父类的方法:

       Dog.prototype.eat = function(foot) {
            Animal.prototype.eat.call(this, foot);
            //在这里写 dog 实现逻辑 dome
            return this.animalName + '不喜欢吃' + foot;
        };
    
        var dog = new Dog();
        dog.eat('老鼠'); //=>狗狗不喜欢吃老鼠
    

    这种实现继承的操作是同类方法中最好的,而且还不会破坏 instanceof 操作符的结果:

        // dog 继承 Animal 前
        var animal = new Animal('狗狗');
        animal instanceof Animal; //=>true
        dog instanceof Animal; //=>false
    
        // dog 继承 Animal 后
        var dog = new Dog();
        animal instanceof Animal; //=>true
        dog instanceof Animal; //=>true
    

    这种实现继承的操作最大不足,就是在声明继承的时候创建对象总需要进行初始化( dog.prototype = new Animal ),这种方式不太友好。解决的办法一种是在构造器中添加判断条件:

        // 定义一个 Animal 类
        function Animal(a) {
            if (false !== a) return;
            //初始化
        }
        // 定义一个要继承Animal的构造器
        function Dog() {}
        // 实现继承
        Dog.prototype = new Animal(false);
    

    另一种就是定义一个空构造器,并向其内重写他的原型:

        // 定义一个 Animal 类
        function Animal() {}
        //定义一个新的空构造器
        function f(){}
        // 定义一个要继承Animal的构造器
        function Dog() {}
        // 重写构造器
        f.prototype = Animal.prototype;
        // 实现继承
        Dog.prototype = new f;
    

    try { ... } catch { ... }

    在函数抛出错误时,代码也会随即停止运行,try/catch 允许进行异常捕获,并抛出异常,并让代码继续执行下去:

        var a = 5;
        try {
            a();
        } catch (e) {
            console.error(e); //=>TypeError: a is not a function
        }
        console.log(a); //=>5
    

    相关文章

      网友评论

          本文标题:【管子先生的Node之旅·3】JavaScript基础复习(三)

          本文链接:https://www.haomeiwen.com/subject/anbrpxtx.html