一、原型
原型的引入是为了解决构造函数浪费内存的问题
- JS规定,每一个构造函数都有一个
prototype
属性,是一个对象,也称为原型对象。 - 构造函数和原型对象中的 this 都指向实例化的对象
二、原型的作用
- 共享方法
- 可以将不变的函数定义在
prototype
对象上,这样所有对象的实例就可以共享这些方法。 - 这个对象可以挂载函数,对象实例不会多次创建原型上函数,节约内存。
三、原型的使用
定义在 prototype 对象上之前:
function Star(uname,age) {
this.uname = uname;
this.age = age;
this.sing = function () {
console.log('唱歌');
}
}
const ldh = new Star('刘德华', 55);
const zxy = new Star('张学友', 58);
console.log(ldh.sing === zxy.sing);
输出:
说明每个实例都指向不同的对象,浪费了内存。
定义在 prototype 之后:
function Star(uname,age) {
this.uname = uname;
this.age = age;
}
Star.prototype.sing = this.sing = function () {
console.log('唱歌');
}
const ldh = new Star('刘德华', 55);
const zxy = new Star('张学友', 58);
ldh.sing();
zxy.sing();
console.log(ldh.sing === zxy.sing);
输出:
说明实例化的对象都指向同一个对象,节省了内存。