一,原型链继承
function A() {
this.name = "jiang";
this.age = 20;
this.method = function () {
console.log("I will be better!")
}
}
A.prototype.like = "paly";
function B() {
}
B.prototype = new A();
var b = new B();
console.log(b.name); //jiang
console.log(b.age); //20
console.log(b.like); //paly
b.method(); //I will be better!
原型链式是创建了A实例并赋给B的原型使B拥有了A的属性和方法,这种继承方式实质是重写了B的原型对象。
二,Object()方法
1,
var person = {
name : "jiang",
age : 19,
car : ['Alto','Ford'],
method1:function () {
console.log("Hi !");
}
};
var anotherPerson = Object(person);
console.log(anotherPerson.name); //jiang
console.log(anotherPerson.age); //19
anotherPerson.car.push('changan');
console.log(anotherPerson.car); //[ 'Alto', 'Ford', 'changan' ]
var yetantherPerson = Object(person);
yetantherPerson.car.push("BMW");
console.log(yetantherPerson.car); //[ 'Alto', 'Ford', 'changan' ]
console.log(person.car); //[ 'Alto', 'Ford', 'changan', 'BMW' ]
object()函数以person对象为原型创建了2个新的对象anotherPerson和yetanotherperson,person中的属性方法为两个对象所共有
相当于创建了两个person的副本。
2,
var anotherperson1 = Object.create(person,{
name : {
value : 'tom'
}
});
console.log(anotherperson1.name); //tom
console.log(anotherperson1.age); //19
var anotherperson2 = Object.create(person,{
color :{
value : ['blue','green']
}
});
console.log(anotherperson2.name); //jiang
console.log(anotherperson2.color); //[ 'blue', 'green' ]
object.create()同上述Object()一样,不过它规范了原型式继承,它有两个参数第一个是要继承的对象,第二个是想要改变或重写的属性,如果超类对象中有相同属性则覆盖其值,没有则创建新的属性
此方法只能覆盖和创建的只是在子类对象中,而不是覆盖和创建在超类中。