JavaScript:在构造函数原型对象上定义公共方法

提出问题

在 构造函数中定义对象的方法,那么,在创建的对象中,都会有该方法,就会占用内存

代码

function Student(name,age){
    this.name = name
    this.age = age
    this.happy = function(){
        this.age ++;
        console.log(this.name+" 过生日,又长大一岁")
    }
}
var lilei = new Student("李雷",20)
console.log("lilei:",lilei)

const hmm = new Student("韩梅梅",21)
console.log("hmm:",hmm)

执行结果如下,2个对象中都有 happy() 方法:

解决

对于公共方法,将其定义在 构造函数的 原型对象 里,这样 构造函数创建的对象,就能 继承 到这些方法

代码

function Student(name,age){
    this.name = name
    this.age = age
}
Student.prototype.happy = function(){
    this.age ++;
    console.log(this.name+" 过生日,又长大一岁")
}

const lilei = new Student("李雷",20)
console.log("lilei:",lilei)

const hmm = new Student("韩梅梅",21)
console.log("hmm:",hmm)

执行结果如下,happy() 方法在 原型对象下()原型对象时同一个):


原文出处:/show_1IX3jNZngbXt.html