ES5的对象创建以及对象继承

一、对象的创建

1、工厂模式

function createPerson(){

       //内部先声明一个新对象,然后定义对象的属性和方法,最后return这个对象

}

var person=createPerson();

2、构造函数模式

function Person(name){//函数名一定大写!!!

       this.name=name;

       this.sayname=function(){

              alert(this.name);

       }

}

var person=new Person("aaaa");

3、原型模式

function Person(){}

Person.prototype={

       name:"aaaa",

       sayname:function(){

              alert(this.name);

       }

}

var person=new Person();

4、组合原型+构造函数(最常用!)

function Person(name){

       this.name=name;

}

Person.prototype={

       constructor:Person,

       sayname:function(){

              alert(this.name);

       }

}

二、对象的继承

1、原型链方法

Subtype.prototype=new Supertype();

2、构造函数方法

function Subtype(){

       Supertype.call(this);

}

3、寄生组合式继承(最常用!)

function Subtype(属性){

       Supertype.call(this,继承的属性);

       this.自有的属性=xxx;

}

Subtype.prototype=new Supertype();

三、举例

//父对象人

function Person(name){

       this.name=name;

}

Person.prototype={

       constructor:Person,

       sayname:funcion(){

               alert(this.name);

       }

}

//子对象老师

function Teacher(name,age){

       Person.call(this,name);

       this.age=age;

}

Teacher.prototype=new Person();

Teacher.prototype={

       constructor:Teacher,

       sayage:function(){

              alert(this.age);

       }

}

猜你喜欢

转载自blog.csdn.net/sanlingwu/article/details/87968319