//以前是这样进行模拟类的
function Persons(name,age){
this.name = name;
this.age = age;
}
//把这个类挂载到全局文件里面
Persons.prototype.showNamess = function() {
return `名字叫做${this.name},年龄${this.age}`
}
new Persons("zeng",22);
let aaa = "cf"
class Person {
constructor(name, age) { //当函数进行调用的时候 会自动的调用这个函数
// console.log(`构造函数执行了 ${name},${age}`)
//这时候必须挂在到这个类上
this.name = name;
this.age = age;
//以前ES5是这样挂载的
// function Person(){this.name= "aaa"}
//Person.prototypes.showName = function(){} 、
//结合上面的 就把属性 name 挂载Person对象里面了
}
//如果写方法的话 以前ES5是挂在 Person.prototypes.setName 现在是直接像java一样
setName() {
return `名字为${this.name}`
}
setAge() {
return `年龄为${this.age}`
}
[aaa]() { //*****这样加上[]后以后就会变成变量了*****
return '逐梦人!!!' //json里面也是可以进行使用的
}
}
let p = new Person("zqj", 22)
console.log(p.setName(), p.setAge()) //记得书写括号 真的是太笨了
console.log(p.cf()) //*****这样就可以进行调用了
console.log(p[aaa]())
//注意
//1.ES6类必须先行定义后在调用没有提升的功能 不然会报错
//下面这样书写代码是会报错的
// let c = new Clazz();
// console.log(c.setName())
// class Clazz{
// constructor(name) {
// this.name = name;
// }
// setName() {
// return this.name = "张三"
// }
// }
//矫正this
// fn.call() fn.apply() fn.bind()
//2.这里介绍一个比较特殊的一个情况
class People {
constructor() {
this.age = 12;
//进行重新指向回去 就是矫正this
this.setAge = this.setAge.bind(this)
}
setAge() {
console.log("this", this)
return `年龄为:${this.age}`
}
}
let pop = new People()
let { setAge } = pop; //进行解构
console.log(setAge())
//ES6还提供了 set设置值 get取值的连个函数
class Area {
//存值 相当于 给bb存一个值
set bb(aaaa) {
console.log(aaaa)
}
//取值
get bb() {
return "好夺目好震撼好炫彩!!!"
}
}
let ar = new Area();
ar.bb = "好嗨哦!感觉人生以及达到了高潮!!!"
console.log(ar.bb)
//静态方法 就是类身上的方法 使用static
class Show {
constructor() {
}
//对象身上的方法
showName() {
return "如果我是DJ!!!"
}
//类身上的方法
static showAge() {
return "这是静态方法"
}
}
let sw = new Show();
console.log(sw.showName())
console.log(Show.showAge())
//继承 父类 子类 继承
//下面是模拟继承的
function Persong(name){
this.name = name;
}
//把这个showA挂载到Person全局上面
Persong.prototype.showA=function() {
return `名字是:${this.name}`
}
//子类
function Student(name,skill){
Persong.call(this,name);//继承
this.skill = skill
}
//把父类的Person挂载Student的全局上
Student.prototype = new Persong()
//这样就得到父亲的方法
let stu = new Student("那个高高大大的男人")
console.log(stu.showA())
//现在ES6里面是这样子的
class fnncs {
//构造方法
constructor(name) {
//往fnn身上挂载一个name
this.name = name;
}
showFnnName() {
return `我是一个名字叫做${this.name}`
}
showB() {
console.log("父亲的showB()方法")
}
}
//子类继承父类的
class childfnncs extends fnncs {
constructor(name,skill) {
//子类必须写明super继承父类的构造方法
super(name);
this.skill = skill;
}
showskill() {
return `skill的技能就是自己skill自己${this.skill}`
}
showB() {
super.showB();
console.log("子类的showB()方法")
}
}
let childfnnc = new childfnncs("强哥","No.1")
console.log(childfnnc.showFnnName())
console.log(childfnnc.showskill())
console.log(childfnnc.showB())