原型链
原型链是实现继承的主要方法,基本思想是利用原型让一个引用类型(Object,Array等)继承另一个引用类型的属性和方法。
基本模式如下:
<script>
function Father(){
this.property = true;
};
Father.prototype.getPro = function(){
return this.property;
};
function Son(){
this.subproperty = false;
};
//继承了Father
Son.prototype = new Father();
var person = new Son();
console.log(person.getPro()); //true
</script>
在通过原型链实现继承时,不能使用对象字面量创建原型方法,这样会重写原型链。
//继承了Father
Son.prototype = new Father();
//使用字面量添加方法 会导致上一条代码无效
Son.prototype = {
getSub : function(){
return this.subproperty;
}
};
var person = new Son();
console.log(person.getPro()) //errors
原型链的问题:
包含引用类型值的原型属性会被所有实例共享。
经典继承:
<script>
function Father(){
this.num = [1,2,3,4];
};
function Son(){
//继承了 Father
Father.call(this);
};
var person1 = new Son();
person1.num.push(5);
alert(person1.num); //1,2,3,4,5
var person2 = new Son();
person2.num.push(6);
alert(person2.num) //1,2,3,4,6
</script>
组合继承:
<script>
function Father(name){
this.name = name;
this.num = [1,2,3,4];
};
Father.prototype.sayName = function(){
alert(this.name);
};
function Son(name,age){
//继承属性
Father.call(this,name);
this.age = age;
};
//继承方法
Son.prototype = new Father();
Son.prototype.constructor = Son;
Son.prototype.sayAge = function(){
alert(this.age);
};
var person1 = new Son('gao',22);
person1.num.push(5);
alert(person1.num); //1,2,3,4,5
person1.sayName(); //gao
person1.sayAge(); //22
var person2 = new Son('liang',23);
person2.num.push(6);
alert(person2.num); //1,2,3,4,6
person2.sayName(); //liang
person2.sayAge(); // 23
</script>
原型式继承:
借助原型可以基于已有的对象创建新对象(必须有一个对象可以作为另一个对象的基础)
使用 Object.create()
<script>
var person = {
name:'gao',
age:[1,2,3]
};
var person1 = Object.create(person);
person1.age.push(4);
var person2 = Object.create(person);
person2.age.push(5);
console.log(person.age); //1,2,3,4,5
</script>
Object.create()返回了一个新对象(person1,person2) ,将person作为原型,新对象的原型中包含引用类型值和基本类型值,所以 age属性会被person1 person2 共享,相当于创建了2个person对象的副本。
总结于JavaScript高级程序设计