组织函数继续
function Animal() {
this.species = "动物";
}
function Cat(name,color) {
this.name = name;
this.color = color;
}
组织函数绑定
function Cat(name,color) {
Animal.apply(this,arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物
prototype形式
Cat.prototype = new Animal();
//Cat.prototype.constructor === Animal;
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黄色");
alert(cat1.species); //动物
PS:假如替换了prototype
,都要为新的prototype
对象加上constructor
属性,并将这个属性指向本来的对象。
直接继续prototype
function Animal(){}
Animal.prototype.species = "动物";
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
与前一种要领比拟,因为不必实行和竖立Animal的实例了,比较省内存
瑕玷:Animal.prototype.constructor === Cat
应用空对象作为中介
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
F是空对象,险些不占内存
拷贝继续
function Animal(){}
Animal.prototype.species = "动物";
function extend(Child,Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for(var i in p){
c[i] = p[i];
}
}
非组织函数的继续
var Chinese = {
nation: '中国'
};
var Doctor = {
career: '大夫'
}
两个对象都是一般对象,不是组织函数,没法运用组织函数要领完成继续
object()要领
function object(o){
function F(){};
F.prototype = o;
return new F();
}把子对象的prototype属性指向父对象
var Doctor = object(Chinese);
Doctor.career = '大夫';
alert(Doctor.nation); // 中国
浅拷贝
function extend(p) {
var c = {};
for(var i in p){
c[i] = p[i];
}
return c;
}
浅拷贝只能拷贝基础范例的数据
深拷贝
可以完成数组和对象的拷贝
function deepCopy(p,c){
var c = 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;
}