首页 > 代码库 > 创建类和对象的方式

创建类和对象的方式

1、简单方式
        
Js代码 
var people ={}; 
Js代码 
      people.name = "steven"; 
      people.age = 23; 
      people.getName = function(){ 
           return "People‘s name is "+ this.name; 
     }; 
console.log(people.getName());          //People‘s name is steven 
console.log(people.age);                    //23 
Js代码 
不好的地方就是:在创建多个对象的场景下会产生 很多冗余的代码,耦合度不高

 

2、工厂模式下

Js代码 
function makePeople(name,age,job){ 
     var _obj = {}; 
     _obj.name = name; 
     _obj.age =age; 
     _obj.job = job; 
    _obj.getName = function(){ 
        return "People‘s name is "+ this.name; 
   }  
    return _obj; 

 
var webdesigner = makePeople("steven",23,"wendesigner"); 
console.log(webdesigner.getName );       //People‘s name is steven 
console.log(webdesigner.job)                //wendesigner 
 

Js代码 
不好的地方就是:实例化比较频繁 

 

3、原型模式(prototype)下
Js代码 
function People(){}; 
People.prototype = { 
       constructor :People, 
       name:"steven", 
       age:23, 
       job:"webdesigner", 
       getName:function(){ 
             return "People‘s name is "+this.name; 
      } 

 
var webdesign = new People(); 
var carman = new People(); 
console.log(webdesign.getName());    //People‘s name is steven 
console.log(carman.getName());    //People‘s name is steven 
 
Js代码 
不好的地方就是:初始化参数不支持传递,还有就是原型的所有属性和方法会被所有的实例共享

 

4、混合模式(原型+构造函数)下

 function People(name.age.job){ 
Js代码 
this.name = name; 
Js代码 
       this.age = age; 
       this.job = job; 
}; 
People.prototype = { 
      constructor:People, 
      getName: function(){ 
           return "People‘s name is "+this.name; 
      } 

 
var webdesigner  = new People("steven",23,"webdesigner"); 
var carman = new People("zyc",24,"carman"); 
console.log(webdesigner.getName())   //People‘s name is steven 
console.log(carman.getName())   //People‘s name is zyc 
 
Js代码 
不好的地方就是:对象的属性和方法也多是公用的

 

5、闭包下的私有变量模式

Java代码 
(function(){ 
    var name =""; 
    People = function(val){ 
        name = val; 
   }; 
    People.prototype ={ 
       constructor:People, 
       getName:function(){ 
              return "People‘s name is "+ name ; 
      } 
   }; 
})(); 

 

var webdesigner = new People("steven"); 
console.log(webdesigner.name);           //undefined 
console.log(webdesigner.getName());      //People‘s name is steven 
 
var carman= new People("zyc"); 
console.log(carman.name);           //undefined 
console.log(carman.getName());      //People‘s name is zyc 
 

Js代码 
不好的地方就是:初级程度代码不是很让人理解 

创建类和对象的方式