//1.function 实现类(最简单的类)
function Person(){
this.name = "张三";
this.age = 12;
}
var p1 = new Person();
console.log(p1.name);
//2.构造函数和原型链
function Person1(){
this.name = "张三";
this.age = 12;
this.run=function(){
console.log(this.name + " is running");
};
}
var p1 = new Person1();
p1.run();
//原型链上的属性和方法会被多个实例共享,构造函数不会
Person1.prototype.sex = "man"; //原型链上定义属性
Person1.prototype.work = function(){//原型链上定义方法
console.log(this.name + "is working");
}
var p2 = new Person1();
console.log(p2.sex);
p2.work();
console.log(p1.sex);
p1.work();
//3.类里的静态方法,即 类方法
Person1.getInfo=function(){
console.log("静态方法,类方法");
}
//4.类中的继承,原型链 和对象冒充
function Person2(){
this.name = "张三";
this.age = 12;
this.run=function(){
console.log(this.name + " is running");
};
}
//对象冒充继承,可以继承构造函数 里的属性和方法,不能继承 原型链上的属性和方法
function Student(){
Person1.call(this);
}
var student1 = new Student();
student1.run();
//原型链上的继承和方法不能继承
//student1.work();
console.log(student1.sex);
//5. 原型链继承,子类即可以继承构造函数属性,也可以继承原型链上的属性和方法
function Student1(){
}
Student1.prototype = new Person1();
console.log("--------原型链继承-----------");
var student2 = new Student1();
student2.run();
student2.work();
console.log(student2.sex);
//6.原型链上继承的问题,不能给父类传参数
function Animal(name,age){
this.name = name;
this.age = age;
this.say=function(){
console.log(this.name + " 在叫~");
}
}
function Cat(name,age){
}
Cat.prototype = new Animal();
var cat1 = new Cat("苗苗",2);
cat1.say();// Cat里的实际参数不能传给Animal
//7.结合冒充继承(构造函数)和原型链继承来实现传参
function Dog(name,age){
Animal.call(this,name,age);
}
//构造函数继承 都可以实现传参
Dog.prototype = new Animal();
//原型链继承
//Dog.prototype = Animal.prototype;
console.log("------构造函数结合原型链继承--------")
var dog1 = new Dog("旺财",3);
dog1.say();