• js面向对象编程(二)


    学习js的笔记,资料来自于阮一峰的Blog。

    如何生成一个“继承”多个对象的实例 。

    1、构造函数绑定

    function Animal() { this.species = 'animal'; }
    function Cat(name, color) {
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
    }
    var cat1 = new Cat('cat1', 'yellow');
    alert(cat1.species);

    2、Prototype模式

    function Animal() { this.species = 'animal'; }
    function Cat(name, color) {
    this.name = name;
    this.color = color;
    }
    Cat.prototype = new Animal();
    Cat.prototype.constructor = Cat;
    var cat1 = new Cat('cat1', 'yellow');
    alert(cat1.species);

    在这个模式中, 我要重点提以下关于constructor。我们都知道当用new 创建一个函数的实例是,函数都会有constructor的属性指向函数本身。但是当修改了prototype对象时,函数的constructor也随之发生了改变。如上例所示,如果不改Cat.prototype.constructor的内容,那么cat1.constructor就为Animal(),否则后面的继承链就会出问题。

    3、直接继承prototype

    function Animal() { }
    Animal.prototype.species = "Animal";
    function Cat(name, color) {
    this.name = name;
    this.color = color;
    }
    Cat.prototype = Animal.prototype;
    Cat.prototype.constructor = Cat;
    var cat1 = new Cat('cat1', 'yellow');
    alert(cat1.species);//Animal

    这种方法比较节省内存,不用再创建Animal的对象了。但是由于Animal和Cat的prototype是同一个对象,所以任何在Cat的prototype上的修改都会影响Animal。所以这中方法是有问题的。不能使用。

    4、利用空对象作为中介

    var F = function () { };
    F.prototype = Animal.prototype;
    Cat.prototype = new F();
    Cat.prototype.constructor = Cat;

    因为F是空对象,几乎不占用内存,即起到了Cat对Animal的继承作用,又可以避免直接new Animal()带来的内存占用。

    可以把上面的方法封装成函数使用。
    5、拷贝继承

    我们其实也可以把父类的对象的所有属性和方法,都拷贝进子对象。

    function Animal(){};
    Animal.prototype.species="Animal";

    function extends(Child, Parent)
    {
      var p = Parent.prototype;
      var c = Child.prototype;
      for(var i in p)
      {
        c[i]=p[i];
      }
    }




  • 相关阅读:
    1、购买阿里云服务器
    struts2页面乱码解决方法
    struts第一次编写怎么都无法跳转页面
    时间转换与map集合
    struts2addActionError 、addFieldError、addActionMessage方法
    struts2基本流程
    struts2自定义类型转换器
    jsp聊天窗口随笔
    conn!=null与conn.isClosed的区别
    应用表单隐藏域进行提交
  • 原文地址:https://www.cnblogs.com/RitaRichard/p/2210547.html
Copyright © 2020-2023  润新知