每一个函数对象都有一个length属性,表示该函数期望接收的参数个数。
关于js面向对象的创建方式,
目标:
构建一个order对象.
包含三个属性:日期,金额,提交人
包含一个方法:显示字符串:”XX在XXXX-XX-XX 提交了额度为:XXXX元的订单"
一 工厂方式
二 构造函数方式
/* 构造函数方式,方法的声明与工厂方式一样,也存在同同样的问题,同样可以提取出来.不同点是声明属性用this 并且需要使用new运算符生成实例. */ function Order() { this.Date = "1990-1-1"; this.Price = "3200"; this.Name = "Vince Keny"; this.Show = function() { alert(this.Name " 在 " this.Date " 提交了额度为 " this.Price " 元的订单.") } } var order = new Order(); order.Show();
三 原型方式
/* 原型方式:使用prototype */ function Order() {} Order.prototype.Date = "1990-1-1"; Order.prototype.Price = "3200"; Order.prototype.Name = "Vince Keny"; Order.prototype.Show = function() { alert(this.Name " 在 " this.Date " 提交了额度为 " this.Price " 元的订单.") } var order = new Order(); order.Show();
四 混合 构造函数/原型 方式
/* 混合构造函数/原型 方式 : 使用构造函数方式初始化属性字段,使用原型方式构造方法. */ function Order() { this.Date = "1990-1-1"; this.Price = "3200"; this.Name = "Vince Keny"; } Order.prototype.Show = function(). { alert(this.Name " 在 " this.Date " 提交了额度为 " this.Price " 元的订单.") } var order = new Order(); order.Show();
五 动态混合方式
/* 动态混合方式 : 和混合方式不同点在于声明方法的位置.将方法生命放到了构造函数内部,更符合面向对象. */ function Order() { this.Date = "1990-1-1"; this.Price = "3200"; this.Name = "Vince Keny"; if(typeof Order._initialized == "undefined") { Order.prototype.Show = function(). { alert(this.Name " 在 " this.Date " 提交了额度为 " this.Price " 元的订单.") }; Order._initialized = true; } } function Car(sColor,iDoors){ var oTempCar = new Object; oTempCar.color = sColor; oTempCar.doors = iDooes; oTempCar.showColor = function (){ alert(this.color) }; return oTempCar; } var oCar1 = new Car("red",4); var oCar2 = new Car("blue",3); oCar1.showColor(); //outputs "red" oCar2.showColor(); //outputs "blue"