原型对象
什么是原型?
每一个对象都有他的原型对象,他可以使用自己原型对象上的所有属性和方法
获取原型的方法
- 通过对象的__proto__获取
例:
let cat = {
name:"喵喵"
}
cat.__proto__.eat = function(){
console.log("吃鱼")
}
cat.eat()
- 通过构造函数的prototype属性拿到原型
例:
function Cat(name,age) {
this.name = name
this.age = age
}
let cat = new Cat("喵喵",2)
Cat.prototype.eat = function (){
console.log("吃鱼")
}
cat.eat()
构造函数中的this指向new创建的对象
原型对象有什么用?
例:
let date = new Date()
Date.prototype.formate = function (){
let year = this.getFullYear()
let month = this.getMonth() + 1
let date = this.getDate()
return `${year}年${month}月${date}日`
}
console.log(date.formate())