javascript中的每个对象都有prototype属性,Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。
A.prototype = new B();
理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方法和属性。这里强调的是克隆而不是继承。可以出现这种情况:A的prototype是B的实例,同时B的prototype也是A的实例。
1.如何继承
//动物
functionAnimal(){
this.species = "动物";
}
//猫
functionCat(name, color){
this.name = name;
this.color = color;
}
2.方法一:构造函数绑定
Animal.apply(this, arguments);//在当前对象中调用函数Annimal
//或Animal.apply(this,[name, color]);
//apply()方法的第二个参数为数组或arguments参数集合
//或Animal.call(this, name, color);(推荐)
//call()方法的第二个及后面可以是任意多个参数
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物
Cat.prototype = new Animal();
//任何prototype对象都有一个constructor属性其构造函数,即,
//没有上一行,Cat.prototype.constructor是指向Cat的;
//加了上一行,Cat.prototype.constructor指向Animal。
//下一行,是将constructor指回原对象构造函数。
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物
4.方法三:直接继承prototype
function Animal(){
}
Animal.prototype.species= "动物";
Cat.prototype =Animal.prototype;
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物
5.方法四:利用空对象作为中介
var F = function(){};
F.prototype =Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
function extend2(Child, Parent) {
var p =Parent.prototype;
var c =Child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;//为了方便在子类中知道它的父类,
uber是一个变量
}
7.方法六:非构造函数继承
nation:'中国'
};
career:'医生'
}
function object(o) { //o为父类,传递进来
functionF() {}
F.prototype = o;
return new F();
}
var Doctor = object(Chinese);
Doctor.career = '医生';
function deepCopy(p, c) {
varc = c || {};
for (var i in p) {
if (typeof p[i] === 'object') {
c[i] = (p[i].constructor === Array) ? [] : {};
deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
}
例如:var Doctor = deepCopy(Chinese);