js面向对象编程(二)

学习js的笔记,资料来自于阮一峰的Blog。

如何生成一个“继承”多个对象的实例 。

1、构造函数绑定

function Animal() { this.species = 'animal'; }
function Cat(name, color) {
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat('cat1', 'yellow');
alert(cat1.species);

2、Prototype模式

function Animal() { this.species = 'animal'; }
function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat('cat1', 'yellow');
alert(cat1.species);

在这个模式中, 我要重点提以下关于constructor。我们都知道当用new 创建一个函数的实例是,函数都会有constructor的属性指向函数本身。但是当修改了prototype对象时,函数的constructor也随之发生了改变。如上例所示,如果不改Cat.prototype.constructor的内容,那么cat1.constructor就为Animal(),否则后面的继承链就会出问题。

3、直接继承prototype

function Animal() { }
Animal.prototype.species = "Animal";
function Cat(name, color) {
this.name = name;
this.color = color;
}
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
var cat1 = new Cat('cat1', 'yellow');
alert(cat1.species);//Animal

这种方法比较节省内存,不用再创建Animal的对象了。但是由于Animal和Cat的prototype是同一个对象,所以任何在Cat的prototype上的修改都会影响Animal。所以这中方法是有问题的。不能使用。

4、利用空对象作为中介

var F = function () { };
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;

因为F是空对象,几乎不占用内存,即起到了Cat对Animal的继承作用,又可以避免直接new Animal()带来的内存占用。

可以把上面的方法封装成函数使用。
5、拷贝继承

我们其实也可以把父类的对象的所有属性和方法,都拷贝进子对象。

function Animal(){};
Animal.prototype.species="Animal";

function extends(Child, Parent)
{
  var p = Parent.prototype;
  var c = Child.prototype;
  for(var i in p)
  {
    c[i]=p[i];
  }
}




原文地址:https://www.cnblogs.com/RitaRichard/p/2210547.html