为啥构造函数的方法要放进原型里而不是直接放在构造函数里呢?
下面代码结果都是一样呀
function person(name,sex,age){
this.name=name
this.sex=sex
this.age=age
}
person.prototype.showSelf=function(){ console.log(`${this.name}${this.age}${this.sex}`)}
let a1 = new person('1','1','1')
let a2 = new person('1','1','1')
a1.showSelf()//111
a2.showSelf()111
function person2(name,sex,age){
this.name=name
this.sex=sex
this.age=age
this.showSelf2=function(){ console.log(`${this.name}${this.age}${this.sex}`)}
}
let b1 = new person2('2','2','2')
let b2 = new person2('2','2','2')
b1.showSelf2()//222
b2.showSelf2()//222
区别
我们是将方法添加到构造函数本身,不是每个实例都需要这种方法,这会导致浪费大量内存空间。因为实例中仍然具有该方法,这占用了每个实例的内存空间。 相反,如果我们只将它添加到原型中,我们只需将它放在内存中的一个位置,但它们都可以访问它。