JavaScript 面向对象之工厂模式

来源:互联网 发布:每个淘宝号最多刷几单 编辑:程序博客网 时间:2024/06/11 12:55

什么是工厂
原料
加工
出厂
工厂方式
用构造函数创建一个类
什么是类、对象(实例):模具和零件

工厂方式的问题

问题
没有new
函数重复定义
加上new
偷偷做了两件事
替你创建了一个空白对象
替你返回了这个对象
new和this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>//用工厂方式构造对象function createPerson(name, sex)    //构造函数{    //1.原料    var obj=new Object();    //2.加工    obj.name=name;    obj.sex=sex;    obj.showName=function ()    {        alert('我的名字叫:'+this.name);    };    obj.showSex=function ()    {        alert('我是'+this.sex+'的');    };    //3.出厂    return obj;}var p1=createPerson('blue', '男');var p2=createPerson('leo', '女');alert(p1.showName==p2.showName);/*p1.showName();p1.showSex();p2.showName();p2.showSex();*/</script></head><body></body></html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title>无标题文档</title>    <script>        function show() {            alert(this);        }        show();     //window        new show(); //新创建的对象    </script></head><body></body></html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script>//用工厂方式构造对象function createPerson(name, sex)    //构造函数{    //假想的系统内部工作流程    //var this=new Object();    this.name=name;    this.sex=sex;    this.showName=function ()    {        alert('我的名字叫:'+this.name);    };    this.showSex=function ()    {        alert('我是'+this.sex+'的');    };    //假想的系统内部工作流程    //return this;}var p1=new createPerson('blue', '男');var p2=new createPerson('leo', '女');/*p1.showName();p1.showSex();p2.showName();p2.showSex();*/alert(p1.showName==p2.showName);</script></head><body></body></html>

参考:JavaScript 面向对象