你可以这样做,但你必须有点偷偷摸摸。我对它的理解是,当您将自制对象存储在 Session 中时,会保留所有数据但会丢失所有功能。要重新获得功能,您必须从会话中“重新补充”数据。
下面是 JScript for ASP 中的一个示例:
<%@ Language="Javascript" %>
<%
function User( name, age, home_town ) {
// Properties - All of these are saved in the Session
this.name = name || "Unknown";
this.age = age || 0;
this.home_town = home_town || "Huddersfield";
// The session we shall store this object in, setting it here
// means you can only store one User Object per session though
// but it proves the point
this.session_key = "MySessionKey";
// Methods - None of these will be available if you pull it straight out of the session
// Hydrate the data by sucking it back into this instance of the object
this.Load = function() {
var sessionObj = Session( this.session_key );
this.name = sessionObj.name;
this.age = sessionObj.age;
this.home_town = sessionObj.home_town;
}
// Stash the object (well its data) back into session
this.Save = function() {
Session( this.session_key ) = this;
},
this.Render = function() {
%>
<ul>
<li>name: <%= this.name %></li>
<li>age: <%= this.age %></li>
<li>home_town: <%= this.home_town %></li>
</ul>
<%
}
}
var me = new User( "Pete", "32", "Huddersfield" );
me.Save();
me.Render();
// Throw it away, its data now only exists in Session
me = null;
// Prove it, we still have access to the data!
Response.Write( "<h1>" + Session( "MySessionKey" ).name + "</h1>" );
// But not its methods/functions
// Session( "MySessionKey" ).Render(); << Would throw an error!
me = new User();
me.Load(); // Load the last saved state for this user
me.Render();
%>
它是一种非常强大的管理保存状态到 Session 的方法,如果需要,可以很容易地为 DB 调用/XML 等替换掉。
有趣的是 Anthony 提出了关于线程的问题,知道他的知识深度,我确信它是正确的并且值得思考,但如果它是一个小站点,您将能够摆脱它,我们已经在一个中型站点上使用了它(每天有 10K 访问者)多年来没有真正的问题。