面向对象

1为一个对象添加属性和方法
var obj=new Object(); obj.name="blue"; obj.sex="男"; obj.showNmae=function(){ alert("我的名字叫:"+this.name); }; obj.showSex=function(){ alert("我是:"+this.sex); }; obj.showNmae(); obj.showSex();

 

  //构造函数对象  用工厂方式构造函数
  function createPerson(name,sex){
    var obj=new Object(); //创建 相当于 原料
    //一系列的内容添加 类似 对原料进行加工
    obj.name=name;
    obj.sex=sex;
    obj.showNmae=function(){
      alert("我的名字叫:"+this.name);
    };
    obj.showSex=function(){
      alert("我是:"+this.sex+"的");
    };
    return obj;//给外面一个接口得到obj; 出口销售
  }
  var p1=createPerson("blue","女");
  var p2=createPerson("red","男");
  p1.showNmae();
  p1.showSex();

  alert(p1.showNmae()==p2.showNmae())?  false;

工厂函数的缺点:

1没有 var p1=createPerson("blue","女");进行new;内容不够简练

2每个对象都有一套自己的方法,造成资源浪费;

 

先解决第一个问题:

 function createPerson(name,sex){
    //在new系统工作假象 createPerson对象过程中
    //他就产生了 var this=new Object();
    this.name=name;
    this.sex=sex;
    this.showNmae=function(){
      alert("我的名字叫:"+this.name);
    };
    this.showSex=function(){
      alert("我是:"+this.sex+"的");
    };
    //new的内部假象 会自己产生返回值
    //return this;
  }
  var p1=new createPerson("blue","女");
  var p2=new createPerson("red","男");
  p1.showNmae();
  p1.showSex();

 在构造函数里添加的是属性
  在原型中添加的方法

 构造对象混合法
  function Person(name,sex){
    this.name=name;
    this.sex=sex;
  }
Person.prototype.showName
=function(){ alert(this.name) } Person.prototype.showSex=function(){ alert(this.sex) } var p1=new Person("blue","男"); var p2=new Person("blue","男"); alert(p1==p2) //解决产生多个对象的问题 p1.showName(); p1.showSex();

 

posted @ 2017-03-22 16:59  niu2016  阅读(99)  评论(0编辑  收藏  举报