javascript 面向对象

  

1、对象

1、基于Obeject

var obj = new Object();

obj.name = 'eric';

obj.age=25;

obj.sex='男';

obj.getName = funtion(){

  return this.name;

 }

2、基于字面量

var obj = {

  name:'eric',

  age: 25,

  sex:'男',

  getName: function(){

    return this.name;

  }

}

2、创建对象方式

 1工厂模式

  function fun(name,age,sex){

    var obj =  new Object();

    obj.name = name;

    obj.age = age;

    obj.sex = sex;

    obj.setName = function(){

      return this.name;

    }

    return obj

  }

  fun('eric',25,'男');

 2构造函数

  function fun(name,age,sex){

    this.name = name;

    this.age = age ;

    this.sex = sex ;

    this.setName = function(){

     return this.name;

    }

  }

  var obj = new fun('eric',25,'男');  

 3原型模式

  function fun(){

  }

  fun.prototype.name = 'eric';

  fun.prototype.age = 25;

  fun.prototype.sex = '男';

  fun.prototype.getName = function(){

    return this.name;

  }

  var obj = new fun();

  var obj1 = new fun();

  obj === obj1 //false(不是同一个obj);

  obj.getName() === obj1.getName() // true (不同object公用一个原型对象方法)

  

 
原文地址:https://www.cnblogs.com/webdugui/p/5438140.html