1,工厂方式:也可以带参数的!每次都要创建新函数showColor(),其实可以在工厂函数外定义该函数,每个对象共享了同一个函数,然后用o.showColor=showColor指向该方法2,构造函数方式function Car(sColor){this.color=sColorthis.showColor=function(){alert(this.color)}}var o1=new Car("red")3,原型方式4,混合的构造函数/原型方式function Car(sColor){this.color=sColorthis.drivers=new Array("mike","sue")}Car.prototype.showColor=function(){alert(this.color)}var o1=new Car("red")o1.drivers.push(“mat”)5,动态原型方法function Car(sColor){this.color=sColorthis.drivers=new Array("mike","sue")}if(typeof Car._initialized=="undefined"){Car.prototype.showColor=function(){alert(this.color)}Car._initialized=true}可以确保该方法只创建一次6,混合工厂模式建议不采用
无法定义这种的js变量
解决思路:
1、由服务器端session对这个变量进行保存,然后再不同页面获取该值
2、保存在cookie中,再不同页面获取,如果保密要求低,推荐这种方式
代码举例:
function setCookie(name,value)
{
var Days = 30
var exp = new Date()
exp.setTime(exp.getTime() + Days*24*60*60*1000)
document.cookie = name + "="+ escape (value) + "expires=" + exp.toGMTString()
}
//读取cookies
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^]*)(|$)")
if(arr=document.cookie.match(reg))
return unescape(arr[2])
else
return null
}
使用
a.html
function add(){ setCookie('name',document.getElementById("yonghuming").value)}
b.html
function huode(){ alert(getCookie('name')) }