生成类和生成实例
class Star {
// 构造函数,接收传递过来的参数,返回实例对象
// 只要new生成实例,就自动调用这个函数,如果不写这个函数,也会自动生成这个函数
constructor(username, age) {
this.username = username;
this.age = age;
}
}
let p = new Star("jack", 19);
console.log(p);
添加共有方法
class Star {
// 构造函数,接收传递过来的参数,返回实例对象
// 只要new生成实例,就自动调用这个函数,如果不写这个函数,也会自动生成这个函数
constructor(username, age) {
this.username = username;
this.age = age;
}
// 创建共有方法
sing(song) {
console.log(this.username + " sing " + song);
}
}
// 创建实例
let p = new Star("jack", 19);
// 调用共有方法
p.sing("盖茨比");
类继承
class Father {
constructor() {}
money() {
console.log(100);
}
}
// 类继承
class Son extends Father {}
let jack = new Son();
jack.money();
super
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
// 类继承
class Son extends Father {
constructor(x, y) {
// 调用父类中的constructor构造函数,将子类的x,y传递给父类
super(x, y);
}
}
let jack = new Son(10, 20);
jack.sum();
调用父类的普通函数及查找原则
class Father {
say() {
console.log("Father");
}
}
class Son extends Father {
// 继承中,实例化子类,会先看子类有没有这个方法,有就执行子类的(就近原则)
// 如果没有再到父类去找这个方法,有就执行
say() {
console.log("son");
}
}
let jack = new Son();
jack.say();
手动调用父类方法
class Father {
say() {
return "Father";
}
}
class Son extends Father {
// 调用父类的普通函数say()
say() {
console.log(super.say());
}
}
let jack = new Son();
jack.say();
Super的位置
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
// 继承父类的加法,同时扩展减法
class Son extends Father {
constructor(x, y) {
// super必须在子类this之前调用
// 必须先调用父类的构造方法吗,再使用子类构造方法
super(x, y);
this.x = x;
this.y = y;
}
subtract() {
console.log(this.x - this.y);
}
}
let jack = new Son(10, 20);
jack.sum();
jack.subtract();
this指向问题
let that;
let _that;
class Star {
constructor(name) {
// constructor 的 this 指向的是创建实例的对象 p ,谁调用指向的就是谁
console.log(this);
that = this;
this.name = name;
this.btn = document.querySelector("button");
// 这里调用sing方法,于是方法里的this指向改变了
this.btn.onclick = this.sing;
}
sing() {
// 这里的 this 是 btn 调用的,所以指向的是btn
console.log(this); // 拿到的是 btn
console.log(that.name); // 拿到 constructor 传过来的 name
}
dance() {
// 这里的this指向的是创建实例的对象,因为this没有改变指向
_that = this;
console.log(_that);
}
}
let p = new Star("jack");
p.dance();
示例
追加元素
<button>点击</button>
<div id="demo">
<ul>
<li>1111</li>
</ul>
</div>
let that;
class Ele {
constructor() {
that = this;
this.btn = document.querySelector("button");
this.main = document.querySelector("#demo");
this.ul = this.main.querySelector("ul");
this.li = this.ul.querySelectorAll("li");
this.btn.onclick = this.addLi;
}
// 动态追加元素
addLi() {
/**
* insertAdjacentHTML() 将指定的文本解析为HTML或XML,并将结果节点插入到DOM树中的指定位置。
* 'beforebegin'元素自身的前面。
* 'afterbegin'插入元素内部的第一个子节点之前。
* 'beforeend'插入元素内部的最后一个子节点之后。
* 'afterend'元素自身的后面。
* */
let random = Math.random();
let li = `<li>${random}</li>`;
that.ul.insertAdjacentHTML("beforeend", li);
}
}
new Ele();