基础语法
添加属性在constructor()函数中 方法写在constructor()外面
class Person {
constructor(name,age){//构造函数(方法),调用new,自动执行
// console.log(`这个人叫${name},冻龄了,永远${age}`)
this.name = name;
this.age = age;
}
showName(){
return `这sb叫${this.name}`;
};
showAge(){
return `这sb年龄是${this.age}`;
}
}
let p1 = new Person("DF",18);
console.log(p1.showName());
console.log(p1.showAge());
class类中的this矫正
一般情况下,class类中的this是比较稳定的,此处如果解构p4会改变this指向
class Person04{
constructor() {
this.name = "DF";
//矫正this的指向
this.showName = this.showName.bind(this);
}
showName(){
console.log("this:",this);
return `名字为:${this.name}`;
}
}
let p4 = new Person04();
class类的静态方法
所谓静态方法就是定义的类本身可调用,其实例不可调用
class Person05{
constructor() {
this.name = "DF"
}
showName(){
return `名字是:${this.name}`
}
static show(){
return `静态方法名字是:${this.name}`
}
}
let p5 = new Person05();
console.log(p5.showName());
console.log(Person05.show());
class类的继承
/*父类*/
class Person06{
constructor(name) {
this.name = name;
}
showName(){
console.log("父类showName");
return `父类名字是:${this.name}`
}
}
/*子类继承*/
class Student extends Person06{
constructor(name,skill){
super(name);//继承对应的属性
this.skill = skill
}
showName(){
super.showName();//当子类和父类方法相同时,子类方法会覆盖父类,想要执行父类方法用super
return `子类名字是:${this.name}`
}
showSkill(){
return `哥们的skill是:${this.skill}`
}
}
let p6 = new Student("LOVE","健身");
console.log(p6.showName());
console.log(p6.showSkill());
使用class类实现拖拽功能
/*普通拖拽*/
class Drag{
constructor(id){
this.oDiv = document.querySelector(id);
this.disX = 0;
this.disY = 0;
this.init();
}
init(){
this.oDiv.onmousedown = function (ev) {
this.disX = ev.clientX - this.oDiv.offsetLeft;
this.disY = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnMove.bind(this);
document.onmouseup = this.fnUp.bind(this);
return false;
}.bind(this);
}
fnMove(ev){
this.oDiv.style.left = ev.clientX - this.disX+"px";
this.oDiv.style.top = ev.clientY - this.disY+"px";
}
fnUp(){
document.onmousemove = null;
document.onmouseup = null;
}
}
/*限制拖拽范围*/
class LimitDrag extends Drag{
fnMove(ev){
super.fnMove(ev);
if(this.oDiv.offsetLeft<=0){
this.oDiv.style.left = 0
}
if(this.oDiv.offsetTop<=0){
this.oDiv.style.top = 0
}
}
}
new Drag("#div1");
new LimitDrag("#div2")