1 var person = function(name){ 2 this.name = name 3 }; 4 person.prototype.getName=function(){//经过person.prototype设置函数对象属性 5 return this.name; 6 } 7 var crazy= new person(‘crazyLee’); 8 crazy.getName(); //crazyLee//crazy继承上属性
在函数内建立一个对象,给对象赋予属性及方法再将对象返回设计模式
1 function Person() { 2 var People = new Object(); 3 People.name = 'CrazyLee'; 4 People.age = '25'; 5 People.sex = function(){ 6 return 'boy'; 7 }; 8 return People; 9 } 10 11 var a = Person(); 12 console.log(a.name);//CrazyLee 13 console.log(a.sex());//boy
无需在函数内部从新建立对象,而是用this指代数组
1 function Person() { 2 this.name = 'CrazyLee'; 3 this.age = '25'; 4 this.sex = function(){ 5 return 'boy' 6 }; 7 8 } 9 10 var a = new Person(); 11 console.log(a.name);//CrazyLee 12 console.log(a.sex());//boy
函数中不对属性进行定义,利用prototype属性对属性进行定义,能够让全部对象实例共享它所包含的属性及方法。函数
function Parent() { Parent.prototype.name = 'carzy'; Parent.prototype.age = '24'; Parent.prototype.sex = function() { var s="女"; console.log(s); } } var x =new Parent(); console.log(x.name); //crazy console.log(x.sex()); //女
原型模式+构造函数模式。这种模式中,构造函数模式用于定义实例属性,而原型模式用于定义方法和共享属性this
1 function Parent(){ 2 this.name="CrazyLee"; 3 this.age=24; 4 }; 5 Parent.prototype.sayname=function(){ 6 return this.name; 7 }; 8 9 var x =new Parent(); 10 console.log(x.sayname()); //Crazy
将全部信息封装在了构造函数中,而经过构造函数中初始化原型,这个能够经过判断该方法是否有效而选择是否须要初始化原型。spa
1 function Parent(){ 2 this.name="CrazyLee"; 3 this.age=24; 4 if(typeof Parent._sayname=="undefined"){ 5 Parent.prototype.sayname=function(){ 6 return this.name; 7 } 8 Parent._sayname=true; 9 } 10 }; 11 12 var x =new Parent(); 13 console.log(x.sayname());