构造函数
function Animal(name) {
this.name = name;
this.eat = function() {
console.log(this.name + "吃老鼠");
}
}
var a = new Animal('猫');
var b = new Animal('狗');
console.log(a.eat == b.eat); //false
![](https://img.haomeiwen.com/i4574403/415380340f2732e8.png)
![](https://img.haomeiwen.com/i4574403/fa62c3ca472f15b9.png)
构造函数生成的对象实例中的方法eat,在各自的实例上面都创建为新的函数,两个函数各自引用自己的内存,造成资源的浪费
prototype
function Person(name) {
this.name = name;
}
Person.prototype.eat = function() {
console.log(this.name + '吃早餐');
}
var aa = new Person('张三');
var bb = new Person('李四');
console.log(aa.eat == bb.eat); //true
![](https://img.haomeiwen.com/i4574403/53ec7b6b7556869f.png)
![](https://img.haomeiwen.com/i4574403/6a7fc43ab4668c6d.png)
prototype生成的对象实例中的方法eat,共同引用Person原型上面的eat方法,节省资源
总结
推荐使用prototype创建对象,更节省内存,更有效率。
网友评论