構造函數
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
貓
狗
構造函數生成的對象實例中的方法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
張三
李四
prototype生成的對象實例中的方法eat,共同引用Person原型上面的eat方法,節省資源
總結
推薦使用prototype創建對象,更節省內存,更有效率。