javascript 面向对象编程(工厂模式、构造函数模式、原型模式)
CreateTime--3月29日17:09:38
Author:Marydon
一、工厂模式
/*** 工厂模式*/function factoryFunction() {// 1.创建一个Object对象(人)var person = new Object();// 或者 var person = {};// 2.对象的属性(对应人的特征)person.name = "Marydon";person.qq = "2982586911";person.website = "/Marydon0307";// 3.对象的方法(对应人的行为)person.operation = function() {alert("正在演示工厂模式"); };return person;}
调用:
factoryFunction().operation();
适用场景:
个人不推荐使用,因为构造函数模式完全可以取代。
二、构造函数模式
/*** 构造函数模式* @注意:首字母要大写,用于和普通函数区分*/function ConstructorFunction() {this.name = "Marydon";this.qq = "2982586911";this.website = "/Marydon0307";// 这个两个this指的是同一对象哦!this.operation = function() {alert(this.name); };}
调用:
// 创建对象,对象创建后,该对象里面的this指的就是cfvar cf = new ConstructorFunction();cf.operation();// 弹出Marydon
适用场景:
个人比较推荐使用
三、原型模式
/*** 原型模式* @注意:使用前,必须实例化*/function prototypeFunction() {};prototypeFunction.prototype.name = "Marydon";prototypeFunction.prototype.qq = "2982586911";prototypeFunction.prototype.website = "/Marydon0307";prototypeFunction.prototype.operation = function() {alert("正在演示原型模式"); };
调用:
// 不能这样直接调用// prototypeFunction().operation();// 必须得先创建这个对象var pf = new prototypeFunction();
适用场景:
给已经存在的对象添加方法时使用
比如:String对象没有trim()方法,Date对象没有format()方法,对其进行自定义封装时,需要用到。
四、还用一种经常使用
/*** 使用JSONObject创建*/var jsonObjectFunction = {name :"Marydon",qq : "2982586911",website : "/Marydon0307",operation : function() {alert("正在演示JSON对象"); }};
调用:
// 直接调用jsonObjectFunction.operation();
适用场景:
比较典型的就是ajax函数对象,另外,许多封装的插件也是使用的这种方式。
五、结语
很多时候需要混合使用,最常见的是:构造函数+原型函数 模式