特性:封装、继承、多态
封装:将数据和对数据的操作集中在一起
继承:一个类型的对象可以访问另一个类型对象的属性和方法
多态:同一个方法作用于不同对象会有不同的结果
原型对象:每一个构造函数都有一个原型对象,每一个原型对象都有一个指向构造函数的指针(constructor);每一个对象实例都有指向原型对象的内部指针(__proto__),原型对象上的属性和方法都能被实例所访问。
封装:
function Person(name,age){
var count = 10; //私有属性
this.name = name; //实例属性
this.age = age;
ths.foo = function(){ //实例方法
console.log(count); //10
}
}
Person.prototype.sayHello = function(){ //原型方法
console.log(this.name); //name值
console.log(count); //报错,无法获取构造函数的私有属性
}
继承:
原型链:
①组合继承
function Person(){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log(this.name);
}
function Male(name,age){
Person.call(this,name,age); //继承实例属性
this.sex = “male”;
}
for(var I in Person.prototype){ //继承原型方法
Male.prototype[i] = Person.prototype[i];
}
Male.prototype.sayHi = function(){
console.log(“aaa”);
}
var male = new Male(“john”,20);
var person = new Person(“jj”,20);
male.sayHello(); //john
male.sayHi(); //aaa
person.sayHi(); //报错 person.sayHi is not a function
②寄生式组合继承
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function(){
console.log(this.name);
}
function Male(name,age){
Person.call(this,name,age); //继承实例属性
this.sex = “male”;
}
Male.prototype = Object.create(Person.prototype); //继承实例方法
Male.protptype.constructor = Male; //使实例方法指向Male
Male.prototype.sayHi = function(){
console.log(“aaa”);
}
var male = new Male(“john”,20);
male.sayHello(); //john
console.log(male.__proto__.constructor); //Male构造函数
③ES6中的继承
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
sayHello(){
console.log(this.name);
}
static foo(){
console.log(“foo”);
}
}
class Male extends Person{
constructor(name,age){
super(name,age); //super实现实例属性的继承,super指向父类的构造函数
}
sayHi(){
super.sayHello(); //super指向父类的原型对象
}
static foo(){
super.foo(); //指向父类
}
}
Var male = new Male(“john”,20);
male.sayHello(); //john
male.sayHi(); //john
Male.foo(); //foo
多态:
console.log(1+2); //3
console.log("1"+"2"); //12