单体创建对象,工厂模式创建对象,构造函数,原型模式

面向对象:是一种编程思想,许多功能事先已经编写好了,在使用时,只需要关注功能的运用,而不需要这个功能的具体实现过程。

单体创建对象

<script type="text/javascript">

var Tom = {

   name:'tom',

   age:18,//写入属性

   showName:function () {

      alert(this.name);

},

      showAge:function () {

         alert(this.age);

}

};//方法

console.log(Tom.name);//调用属性

console.log(Tom.age);

Tom.showName();//调用方法

</script>

工厂模式创建对象

<script type="text/javascript">

function Person(name,age,job) { //函数名开头大写

   //var o = new Object();//创建一个空对象

   var o ={};//创建一个空对象,一般使用这个

   o.name = name;

   o.age = age;

   o.job = job;

   o.showName = function () {

      alert(this.name);

};

   o.showAge = function () {

      alert(this.age);

};

   o.showJob = function () {

      alert(this.job);

};

   return o;

}

var Tom = Person('tom','18','程序猿');

Tom.showJob();

var Jack = Person('Jack','18','程序猿');

Jack.showJob();

var Esther = Person('esther','18','啦啦啦');//写入属性

Esther.showJob();//调用方法 调用Esther的showJob属性

</script>

构造函数

<script type="text/javascript">

// class Person(object):

// def __init__(name,age,job):

//   self.name = name

//   self.age = age

//   self.job = job

// def showName(self):

 //   print(self.name)

function Person(name,age,job){

      this.name = name;//this代表实例化的

      this.age = age;

      this.job = job

      this.showName = function(){

         alert(this.name);

};

      this.showAge = function(){

         alert(this.age);

};

      this.showJob = function(){

         alert(this.job);

};

}

   var Jack = new Person('jack','18','产品汪');

   Jack.showJob();

   var Esther = new Person('esther','18','lll');

   Esther.showJob();

</script>

原型模式

<script type="text/javascript">

function Person(name,age,job){

      this.name = name;

      this.age = age;

      this.job = job;

}

   // 所有是实例共享(原型)

   Person.prototype.showName = function () {

      alert(this.name);

};

   Person.prototype.showAge = function () {

      alert(this.age);

};

   Person.prototype.showJob = function () {

      alert(this.job);

};

   var Esther = new Person('esther',18,'lll');//var 指向showAge showJob showName

   Esther.showJob = function () {

      alert('我的工作是'+this.job)//调用时先找自己的

   };

   var Jack = new Person('jack',18,'啦啦啦');

   Esther.showJob();

   Jack.showJob();

</script>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容