// js 类class详解 参考 https://zhuanlan.zhihu.com/p/231813098
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
// 自定义属性 可以被继承
obj = {
a: '小胡',
b: '小李'
}
getInfo() {
console.log('父类中的获取信息方法')
return `${this.name}今年${this.age}了`
}
//静态方法 只能通过类名来调用,同样可以被继承
static staticFunc() {
console.log('这是一个静态方法')
}
}
const p1 = new Person('王磊', 19)
// 为类增加方法的三种方法
// 1、在类的原型上添加方法,注意此方法不可使用箭头函数,否组this会指向window
Person.prototype.getAge = function () {
console.log(this, this.age)
}
// 2、使用Object.assgin()方法
Object.assign(Person.prototype, {
getName() {
console.log(this, this.age)
},
setName(val) {
this.name = val
console.log(this, this.name)
}
})
// 3、使用实例对象的__proto__方法
p1.__proto__.eat = function () {
console.log(this, '此方法通过__proto__创建')
}
// 实例 -> 类(构造函数)-> 构造函数的原型对象
// 实例.__proto__ === 类.prototype
// console.log(p1.__proto__ === Person.prototype) > true
// p1.getAge()
// p1.getName()
// p1.setName('小李')
// p1.eat()
// 继承 extends
class Student extends Person {
constructor(name, age, hobbie) {
//子类中若想使用constructor构造函数需要首先调用super()方法
//调用super()方法后,父类constructor函数中的属性清空,需要重新定义
super()
this.name = name
this.age = age
this.hobbie = hobbie
}
// 重写父类的方法
getInfo() {
//super.父类中方法名() 调用父类中的同名方法
// super.getInfo()
return `${this.name}今年${this.age}了`
}
hobbies() {
return `${this.name}喜欢${this.hobbie}`
}
}
const stu1 = new Student('小胡', 20, '打篮球')
// console.log(stu1.obj)
// console.log(stu1.hobbies())
// console.log(stu1.getInfo())
//静态方法的调用
// Person.staticFunc()
// Student.staticFunc()
// ES5中创建类的方法
function Animals(name) {
this.name = name
}
const cat = new Animals('Cat')
Animals.prototype.eat = function() {
console.log(`${this.name}吃饭了`)
}
cat.__proto__ = Animals.prototype
// cat.eat()
for(var prop in cat){
console.log(prop);//name、age、job、sayName
}
console.log(Object.keys(cat)) //实例的
console.log(Object.keys(Animals.prototype))
console.log(Object.getOwnPropertyNames(Animals.prototype))
console