prototype:
当每创建一个类的实例的时候,都要执行一次构造函数,函数中的属性和方法总会被重复创建,prototype可以很好的解决。当new一个function时,该对象的成员将自动的赋给所创建对象。prototype发生在函数体(构造器)执行之前。prototype的定义必须在new实例化对象之前,否则不会起作用。
<
HTML
>
< HEAD >
< TITLE > Test JavaScript Function example </ TITLE >
</ HEAD >
< BODY >
< script >
var userA;
var userB;
function User(name,age)
{
this .str_name = name;
this .str_age = age;
}
User.prototype.sayage = function ()
{
alert( this .str_age);
}
function testUser()
{
userA = new User( " Tomseon " , " 27 " );
userA.sayage();
// userA.sayme(); //Prototype definition must before new instance of the object, otherwise they would not work
User.prototype.sayme = function ()
{
alert( this .str_name);
}
userB = new User( " mike " , " 20 " );
userB.sayage();
userB.sayme();
}
</ script >
< input type ="reset" name ="Submit" id ="Button1" value ="testUser" onclick ="testUser()" >
</ BODY >
</ HTML >
< HEAD >
< TITLE > Test JavaScript Function example </ TITLE >
</ HEAD >
< BODY >
< script >
var userA;
var userB;
function User(name,age)
{
this .str_name = name;
this .str_age = age;
}
User.prototype.sayage = function ()
{
alert( this .str_age);
}
function testUser()
{
userA = new User( " Tomseon " , " 27 " );
userA.sayage();
// userA.sayme(); //Prototype definition must before new instance of the object, otherwise they would not work
User.prototype.sayme = function ()
{
alert( this .str_name);
}
userB = new User( " mike " , " 20 " );
userB.sayage();
userB.sayme();
}
</ script >
< input type ="reset" name ="Submit" id ="Button1" value ="testUser" onclick ="testUser()" >
</ BODY >
</ HTML >