JavaScript:在构造函数原型对象上定义公共方法 作者:马育民 • 2022-07-23 21:43 • 阅读:10028 # 提出问题 在 构造函数中定义对象的方法,那么,在创建的对象中,都会有该方法,就会占用内存 [](/upload/0/0/1IX3jNQsiwzW.png) ### 代码 ``` 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()` 方法: [](/upload/0/0/1IX3lR1JyxuO.png) # 解决 对于公共方法,将其定义在 构造函数的 **原型对象** 里,这样 构造函数创建的对象,就能 继承 到这些方法 [](/upload/0/0/1IX3jNZAlmNo.png) ### 代码 ``` 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()` 方法在 原型对象下()原型对象时同一个): [](/upload/0/0/1IX3lR4L7xUX.png) 原文出处:http://www.malaoshi.top/show_1IX3jNZngbXt.html