構(gòu)造函數(shù)
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
構(gòu)造函數(shù)生成的對象實(shí)例中的方法eat,在各自的實(shí)例上面都創(chuàng)建為新的函數(shù)正卧,兩個函數(shù)各自引用自己的內(nèi)存蠢熄,造成資源的浪費(fèi)
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
prototype生成的對象實(shí)例中的方法eat,共同引用Person原型上面的eat方法炉旷,節(jié)省資源
總結(jié)
推薦使用prototype創(chuàng)建對象签孔,更節(jié)省內(nèi)存,更有效率窘行。