原型的概念
原型是一个对象、prototype也称之为原型对象
原型的作用
- 共享方法
- 可以把那些不变的方法直接定义到prototype原型上
构造函数和原型中的this
构造函数和原型中的this指向实例化对象
// 构造函数
// 公共的函数写到构造函数里面
let that
function Goods(name, price, count) {
that = this
console.log(that); //原型对象
this.name = name,
this.price = price, // 属性、方法前必须加this,this表示当前运行时的对象
this.count = count
// this.sing = function () {
// console.log('我会跳舞');
// }
}
// 原型
// 公共的方法写到原型里面
Goods.prototype.sing = function () {
that = this
console.log('我会跳舞'); //原型对象
}
// 修改实例对象
const GoodsName = new Goods("name", 1200, 90);
const GoodsName2 = new Goods("name", 1200, 90);
// 打印
console.log(GoodsName.sing == GoodsName2.sing); //true
GoodsName.sing() //我会跳舞
原型的继承
// 构造函数
function person() {
this.eyse = 2,
this.header = 1
}
console.log(new person());
function Mansex() {
}
function Man() {
}
// 都是通过原型来继承
// 父级构造函数(父类) = 子构造函数(子类)
// 子类的原型 = new 父类
Mansex.prototype = new person()
Mansex.prototype.constructor = Mansex
Man.prototype = new person()
Man.prototype.constructor = Man
// 给Man添加一个方法
Man.prototype.baby = function () {
console.log('加人口')
}
const ldh = new Mansex()
const jjy = new Man()
console.log(ldh);
console.log(jjy);
总结
prototype(原型对象)
// 构造函数
// 公共的函数写到构造函数里面
function Goods(name, price, count) {
this.name = name,
this.price = price, // 属性、方法前必须加this,this表示当前运行时的对象
this.count = count
}
// 原型
// 公共的方法写到原型里面
Goods.prototype.sing = function () {
console.log('我会跳舞');
}
// 修改实例对象
const GoodsName = new Goods("name", 1200, 90);
const GoodsName2 = new Goods("name", 1200, 90);
// 打印
console.log(GoodsName); //name:name,price:1200,count:90
console.log(GoodsName.sing == GoodsName2.sing); //true
console.log(GoodsName.sing); //ƒ () {console.log('我会跳舞');}
console.log(GoodsName2.sing); //ƒ () {console.log('我会跳舞');}
constructor(构造函数)
constructor在原型对象里面存在的、该属性指向父级原型对象的构造函数,简单理解(指向我的爸爸,我是有爸爸的孩子)
使用场景
let that
function Goods(name, price, count) {
that = this
console.log(that); //原型对象
this.name = name,
this.price = price, // 属性、方法前必须加this,this表示当前运行时的对象
this.count = count
}
Goods.prototype = {
constrouctor:Goods, //加与不加的区别,不加没有指向父级
sing: function () {
console.log('藏');
},
tang: function () {
console.log('跳舞');
}
}
console.log(Goods.prototype);
console.log(Goods.prototype.constructor);
console.log(Goods.prototype.constructor == Goods);
加前的效果
加后的效果
对象原型(proto)
对象都会有一个属性__protto__指向构造函数的 prototype 原型对象,之所以我们对象可以使用构造函数 prototype 原型对象的属性和方法,就是因为对象有__proto__原型的存在。
function Star(){}
const ldh = new Star()
console.log(ldh);
// 对象原型__proto__指向该构造函数的原型对象
console.log(ldh.__proto__);
console.log(ldh.__proto__ == Star.prototype);