Wednesday, February 18, 2015

Javascript - Inheritance

Firstly define two construction functions
function Animal(){
this. species = "animal";
}

function Cat(name, color){
this.name = name;
this.color = color;
}

构造函数绑定
1. 使用call或者apply方法,将父对象的构造函数绑定在子对象上
function Cat(name, color){
Animal.apply(this, arguments);
this.name = name;
this.color = color; 
}

var cat1 = new Cat("sharon", "white");
alert(cat1.species);//animal

note:
Function.apply(obj, args)方法能接受两个参数
obj: 这个对象将代替Function类里的this对象
args: 这个是数组,它将作为参数传给Function

2.prototype
Cat.prototype = new Animal(); //Cat的prototype对象指向一个Animal实例
//任何一个prototype对象都有一个constructor属性,指向它的构造函数
//Cat.prototype.constructor指向Animal
//使用new之后,每一个实例也有一个constuctor属性,默认调用prototype的constructor属性
//因此需要手动改回指向原来的构造函数
Cat.prototype.constructor = Cat;

******如果替换了prototype对象,需要为新的p'ro'totype加上constructor属性,指回原来的构造函数******
 o.prototype = {};
 o.prototype.constructor = o;

3.直接继承prototype
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat; //此句把Animal.prototype的对象的constructor属性也改掉了
//问题是Cat.prototype和Animal.prototype指向同一对象,任何对Cat.prototype的修改会直接反映到Animal.prototype上

非构造函数的继承
//把子对象的prototype属性指向父对象,使得子对象和父对象连在一起
function object(o){
function F(){}
F.prototype = o;
return new F();
}
var Doctor = object(Chinese);
Doctor.career='doctor';



浅拷贝?深拷贝?http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_inheritance_continued.html

No comments:

Post a Comment