面向对象的继承(拷贝继承)

来源:互联网 发布:java反射调用方法 编辑:程序博客网 时间:2024/04/30 14:58

什么是继承

  1. 在原有对象的基础上,稍微修改后得到新的对象
  2. 不会影响原对象的功能
    (子类不影响父类,子类可以继承父类的一些功能)
  • 属性继承

调用父类的构造函数,使用call方法改变this指向问题。

  • 方法继承

for in 拷贝继承(extend)

  function CreatePerson(name,sex) {       this.name = name;        this.sex = sex;    }    CreatePerson.prototype.showName = function() {        alert(this.name);    }    var p1 = new CreatePerson('张三','男');    p1.showName();    function CreateStar(name,sex,job) {        CreatePerson.call(this,name,sex);    }    extend(CreateStar.prototype,CreatePerson.prototype)    function extend(obj1,obj2) {        for (var attr in obj2) {            if (obj2.hasOwnProperty(attr)) {                obj1[attr] = obj2[attr];            }        }    }    var p2 = new CreateStar('李四','男','演员');    p2.showName();

继承拖拽

 function Drag(id) {      this.obj = document.getElementById(id);      this.disX = 0;      this.disY = 0;  }  Drag.prototype.init = function() {      var _this = this;      this.obj.onmousedown = function() {          var ev = ev || window.event;          _this.downFn(ev);          return false;      };  }  Drag.prototype.downFn = function(ev) {      var _this = this;      this.disX = ev.pageX - this.obj.offsetLeft;      this.dixY = ev.pageY - this.obj.offsetTop;     document.onmousemove = function() {          var ev = ev || window.event;          _this.moveFn(ev);      }      document.onmouseup = function() {          _this.upFn();      }  }  Drag.prototype.moveFn = function(ev) {      var L = ev.pageX - this.disX;      var T = ev.pageY - this.disY;      var maxL = document.documentElement.clientWidth - this.obj.clientWidth;      var maxH = document.documentElement.clientHeight - this.obj.clientHeight;      if (L < 0) {          L = 0;      } else if (L > maxL) {          L = maxL;      }      if (T < 0) {          T = 0;      } else if (T > maxH) {          T = maxH;      }      this.obj.style.left = L + 'px';      this.obj.style.top = T + 'px';  }  Drag.prototype.upFn = function() {      document.onmousemove = null;      document.onmouseup = null;  }  function Drag2(id) {      Drag.call(this,id);  }  extend(Drag2.prototype,Drag.prototype);  Drag2.prototype.moveFn = function(ev) {      var L = ev.pageX - this.disX;      var T = ev.pageY - this.disY;      this.obj.style.left = L + 'px';      this.obj.style.top = T + 'px';  }  function extend(obj1,obj2) {      for (var attr in obj2) {          if (obj2.hasOwnProperty(attr)) {              obj1[attr] = obj2[attr];          }      }  }  window.onload = function() {      var drag = new Drag('box');      drag.init();      var drag2 = new Drag2('box1');      drag2.init();  }
0 0
原创粉丝点击