面向对象语言【33】---工厂模式 【34】----构造函数

来源:互联网 发布:php网页源代码加密 编辑:程序博客网 时间:2024/06/09 20:31
<!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=gb2312" />
<title>面向对象语言</title>
<script>
/*var box=new Object(); //创建对象
box.name="lee";   //创建属性
box.age="2012";
box.run=function(){return this.name+this.age} //创建方法方法,this表示实例化出来的那个对象,this要放在一个作用域下,如box.run(){};这个事box作用域下的方法菜能运行,
                                                  //方可用他 this表示box

alert(box.run());  //引用方法需要加(),例如run(),run表示地址
alert(this.name);   //这里的this表示window,所以显示为unfinished;
*/


/*
//普通实例对象化,会产生大量重复的代码;
var  box=new Object();
box.name="lee";
box.age="2012";
box.run=function(){return this.name+this.age};
alert(box.run);
var box1=new Object();
box1.name="kk";
box1.age="2012";
box.run=function(){return this.name+this.age;}
*/
//为了解决多个类似声明的方法,我们可以使用一种叫做工厂模式的方法,这种方法就是为了解决实例化对象产生大量重复代码的问题
/*function createObject(name,age){
var obj=new Object();  //创建对象
obj.name=name;
obj.age=age;  //添加属性
obj.run=function(){           // 添加方法
return this.name+this.age+"正在运行中..";
}
return obj;              //返回对象(必须的,否则后面无法引用)
}
var box1=new createObject("Lee",1000);  //创建对一个对象
var  box2=new createObject("kk",2000);   //创建对二个对象
alert(box1.run());
alert(box2.run());
alert(typeof box1);
alert(typeof box2);
alert(box1 instanceof Object); // 不管怎样,他们都Object,无法区分他们

alert(box2 instanceof Object); */

//构造函数(是工厂模式的升级)
function Box(name,age){  //创建一个构造对象,其实所有的构造函数都是一个Object;
this.name=name;
this.age=age;
this.run=function(){          
return this.name+this.age+"正在运行中..";
}
};
//构造函数没有new Object,但他的后台会自动产生一个 var obj=new Object();
//this相当于obj;
//构造函数不需要return对象引用
//构造函数规范
//构造函数也是函数,但函名数的第一个字母需要大写
//必须使用new构造函数,newBox(),而且这个Box字母也需要大写
//必须使用new运算符

var box1=new Box("JK","22");  //实例化
var box2=new Box("MK","30");
var box3=new Object("MK","30");
alert(box1.run());    //这里切记必须是run(),如果把()忘记了,就直接alert“function(){   return this.name+this.age+"正在运行中..";”;run()代表的是函数sun()里面的值,sun代表的是这个函数
alert(box1 instanceof Object);
alert(box1 instanceof Box);   //可以识别,是否属于某个对象,工厂模式是不能识别的
alert(box2 instanceof Box);
alert(box3 instanceof Box);//false

/*

//面向对象函数,的函数是需要封装的,不能随便改动,改动的只需函数外调动
function Box(user,age){  //普通对象的对象名首字母不要大写
this.user=name;
this.age=age;
this.sun=function(){       //这里的this是局部变量,this==BOX();
return this.user+this.age+"运行中.....";
}
}
alert(Box("KK","35"));//false,构造函数使用一般函数调用时无需的,必须使用new运算符;

*/

</script>
</head>
<body> 
</body>
</html>
0 0
原创粉丝点击