javascript工厂方式定义对象
每一个函数对象都有一个length属性,表示该函数期望接收的参数个数。
<html>
<head>
<scripttype="text/javascript">
varadd=function(num1,num2,num3){
alert(num1+num2+num3);
}
alert(add.length);
</script>
</head>
<body>
</body>
</html>
关于js面向对象的创建方式,
目标:
构建一个order对象.
包含三个属性:日期,金额,提交人
包含一个方法:显示字符串:”XX在XXXX-XX-XX提交了额度为:XXXX元的订单"
一工厂方式
<scripttype=text/javascript>
/*
工厂方式:通过使用方法返回对象,使用时不需要通过new生成新对象.
*/
functioncreateOrder()//也可以构建带参数的工厂方法,根据传入的参数初始化对象数据.
{
varorder=newObject();
order.Date="1990-1-1";
order.Price="3200";
order.Name="VinceKeny";
order.Show=function()//将show方法放在工厂中,则分别为每个实例创造一个Show方法.浪费资源是此模式的弊端.
{
alert(this.Name+"在"+this.Date+"提交了额度为"+this.Price+"元的订单.")
}
returnorder;
}
//使用工厂模式返回对象:
varorder= createOrder();
//也可以这样使用,把工厂模式改造成"伪构造函数",因为在工厂中使用了new,所以创建对象时的new运算符将被忽律.
varorder2=newcreateOrder();
order.Show();
order2.Show();
</script>
二构造函数方式
/*
构造函数方式,方法的声明与工厂方式一样,也存在同同样的问题,同样可以提取出来.不同点是声明属性用this
并且需要使用new运算符生成实例.
*/
functionOrder()
{
this.Date="1990-1-1";
this.Price="3200";
this.Name="VinceKeny";
this.Show=function()
{
alert(this.Name+"在"+this.Date+"提交了额度为"+this.Price+"元的订单.")
}
}
varorder=newOrder();
order.Show();
三原型方式
/*
原型方式:使用prototype
*/
functionOrder()
{}
Order.prototype.Date="1990-1-1";
Order.prototype.Price="3200";
Order.prototype.Name="VinceKeny";
Order.prototype.Show=function()
{
alert(this.Name+"在"+this.Date+"提交了额度为"+this.Price+"元的订单.")
}
varorder=newOrder();
order.Show();
四混合构造函数/原型方式
/*
混合构造函数/原型方式:使用构造函数方式初始化属性字段,使用原型方式构造方法.
*/
functionOrder()
{
this.Date="1990-1-1";
this.Price="3200";
this.Name="VinceKeny";
}
Order.prototype.Show=function().
{
alert(this.Name+"在"+this.Date+"提交了额度为"+this.Price+"元的订单.")
}
varorder=newOrder();
order.Show();
五动态混合方式
/*
动态混合方式:和混合方式不同点在于声明方法的位置.将方法生命放到了构造函数内部,更符合面向对象.
*/
functionOrder()
{
this.Date="1990-1-1";
this.Price="3200";
this.Name="VinceKeny";
if(typeofOrder._initialized=="undefined")
{
Order.prototype.Show=function().
{
alert(this.Name+"在"+this.Date+"提交了额度为"+this.Price+"元的订单.")
};
Order._initialized=true;
}
}
functionCar(sColor,iDoors){ varoTempCar=newObject; oTempCar.color=sColor; oTempCar.doors=iDooes; oTempCar.showColor=function(){ alert(this.color) }; returnoTempCar; } varoCar1=newCar("red",4); varoCar2=newCar("blue",3); oCar1.showColor(); //outputs"red" oCar2.showColor(); //outputs"blue"