js中定义类或对象一般使用“构造函数+原型”方式:用构造函数定义所有非方法的成员,用原型定义方法成员
js中的继承有三种方法,对象冒充,原型链,对象冒充+原型链
/** 1、对象冒充 将Parent中执行的this绑定到对象child上
//写法1
function Parent(){
this.name="parent";
this.sayName = function (){
alert("I am "+this.name);
}
}
function Child(){
this.name="child";
}
var child = new Child();
Parent.call(child);
child.sayName();
//写法2
function Parent(){
this.name= "parent";
this.sayName = function (){
alert(" I am "+this.name);
}
}
function Child (){
this.age="26";
Parent.call(this);
}
var child = new Child();
child.sayName();
alert(child.name+" "+child.age);
/** 2、 原型链 */
function Parent (){
this.name = "parent";
this.age = "54";
}
function Child1 (){
this.name = "child1"
this.point = "北京";
this.salary = "3500";
}
Child1.prototype = new Parent();//
var child1 = new Child1();
alert(child1.name+" "+child1.point+" "+child1.salary);
function Child2(){
this.point = "哈尔滨";
this.salary = "5000";
}
Child2.prototype = new Parent();
var child2 = new Child2();
alert(child2.name+" "+child2.point+" "+child2.salary);
/** 3、对象冒充+原型链 */
//实现继承一般使用“对象冒充(object masquerading)+原型链”方式:用对象冒充继承构造函数的所有成员,用原型链继承原型的方法(用了原型链,instanceOf运算符才有效)。
Animal.prototype.ShowName = function() {
alert(this.name);
}
function Animal(animalName){
this.name = animalName;
}
function Bird(birdName,birdColor){
Animal.call(this,birdName);
this.color = birdColor;
}
Bird.prototype = new Animal();
Animal.prototype.age = "10";
Bird.prototype.ShowColor = function (){
alert(this.color);
}
var bird = new Bird("gugu","red");
bird.ShowName();
bird.ShowColor();
alert(bird.age);