类-继承
ES5中的继承方式
- 普通的继承方式
//父类
function Father(name) {
this.name = name;
}
Father.prototype.showName function() {
return `名字是:${this.name}`;
}
//子类
function Son(name,age) {
Father.call(this,name);
this.age = age;
}
Son.prototype = new Father();
Son.prototype.showAge = function() {
return `年龄是:${this.age}`;
}
//调用
let person = new Son("qwe","12");
console.log(person.name,person.age);//qwe 12
console.log(person.showName());//名字是:qwe
- 圣杯模式实现继承
var inherit = (function (){
var F = function () {};
return function (Target,Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constuctor = Target;
Target.prototype.uber = Origin.prototype;
}
});
ES6中实现的继承
class Father {
constructor(name) {
this.name = name;
}
showName() {
return `名字为:${this.name}`;
}
static showMale() {//静态方法
console.log(`xxxxxx`);
}
}
class Son extends Father{
constructor(name,age){
super(name);
this.age = age;
}
showName() {
super.showName();//调用父类的方法
}
showAge() {
return `年龄是:${this.age}`;
}
}
let person = new Son("asd",34);
console.log(person.showName(),person.showAge());//名字为:asd 年龄是:34
console.log(Son.showMale());//xxxxxx
- 在子类中如果有函数名与父类一样的方法会重写父类的方法,通过super调用父类的方法后就不会重写,也可实现子类的方法。
- 在方法前面加static后这个方法不会被实例继承,子类可以继承该方法
小练习
对方快实现拖拽
<div id="div1" class="box left">DIV1</div>
<div id="div2" class="box right">DIV2</div>
class Drag {
constructor(id) {
this.div = document.querySelector(id);
this.disX = 0;
this.disY = 0;
this.init();
}
init() {
this.div.onmousedown = function(e) {
this.disX = e.clientX - this.div.offsetLeft;
this.disY = e.clientY - this.div.offsetTop;
document.onmousemove = this.Move.bind(this);
document.onmouseup = this.Up.bind(this);
return false;//阻止默认事件
}.bind(this);
}
Move(e) {
this.div.style.left = e.clientX - this.disX + 'px';
this.div.style.top = e.clientY - this.disY + 'px';
}
Up() {
document.onmousemove = null;
document.onmouseup = null;
}
}
//设置拖拽不能越界
class allDrag extends Drag{
Move(e){
super.Move(e);
if(this.div.offsetLeft <= 0){
this.div.style.left = 0;
}else if(this.div.offsetTop <= 0) {
this.div.style.top = 0;
}
}
}
new Drag("#div1");
new allDrag("#div2");