原文网址:http://blog.sina.com.cn/s/blog_4c81e6230100z0kn.html
代码:
function Cat() {
}Cat.prototype = {constructor: Cat,say: function (msg) {
console.log(msg);},add: function (a, b) {
console.log(a + b);},data: [1, 2, 3, 4]}var s1 = new Cat();var s2 = new Cat();console.log(s1.data);s2.data.push('sd');
console.log(s1.data);console.log(s1.say === s2.say);//运行结果:
//[1, 2, 3, 4]
//[1, 2, 3, 4, "sd"]
// true
原型模式优点
1. 减少内存消耗,系统资源占用少,所有实例共享同一方法,不会创建多个
2. 原型对象继承时,子类在重写父类原型方法时很方便,可以很方便 调父类房法,再扩展。
原型模式缺点
1. 优点1既是最大的优点,也同样带来一个严重问题,如果共享的对象是引用对象(如array)则也会造成多个实例共享同一个array,很可能会相互影响
构造函数模式:
代码:
function Cat() {
this.data = [1, 2, 3, 4];
this.say = function (msg) {
console.log(msg);
}
}
var s1 = new Cat();
var s2 = new Cat();
console.log(s1.data);
s2.data.push('sd');
console.log(s1.data);
console.log(s1.say === s2.say);
//动运结果:
// [1, 2, 3, 4]
// [1, 2, 3, 4]
//false
缺点
1. 每一次实例化,该对象内部函数都会被创建一遍。
2. 对象继承并需要在子类中调用父类的方法是不可能的,只可以覆盖或者使用。
优点:
每个实例的公共对象都是不同的,不会相互影响。
当然最常用的方式还是结合二者优缺点,取长不断:
在继承中的区别:
原型模式:
function Cat() {
// array引用类型使用构造函数模式
this.data = [1, 2, 3, 4];
alert('cat');
}
Cat.prototype = {
constructor: Cat,
say: function (msg) {
console.log(msg);
},
add: function (a, b) {
console.log(a + b);
}
}
function TomCat() {
this.me = 25;
alert('tom');
}
TomCat.prototype = new Cat(); //继承Cat的Prototype
//TomCat.prototype.constructor = TomCat;
//重写add方法
TomCat.prototype.add = function (a, b) {
//调用父类方法
Cat.prototype.add(a, b);
//
alert(a + b);
}
var s1 = new Cat();
var s2 = new Cat();
console.log(s1.data);
s2.data.push('ss');
console.log(s1.data);
而在构造函数模式:
function Cat() {
this.say = function (msg) {
console.log(msg);
}
}
function Tom() {
Cat.apply(this, arguments);
this.say = function (msg) { //我在重写say这个公共方法,但是又不想从头实现,只是想在原有功能基础上扩展,没办法调用父类的say方法啊
alert(msg);
}
}
Tom.prototype = new Cat();
var s2 = new Tom();
s2.say('2555');