请问如下两段代码有何不同,谢谢!
一:
function ValidateEventArgs()
{
this.results = new Array();
this.checkedObjects = new Array();

ValidateEventArgs.prototype.getResult = function()
{
var msg = "";

for (var i = 0; i < this.results.length; i++)
{
msg += this.results[i].getMessage() + "\n";
}
return msg;
}
}
二:
function ValidateEventArgs()
{
this.results = new Array();
this.checkedObjects = new Array();
}
ValidateEventArgs.prototype.getResult = function()
{
var msg = "";

for (var i = 0; i < this.results.length; i++)
{
msg += this.results[i].getMessage() + "\n";
}
return msg;
}另外请问这个是什么意思呢?
ValidateEventArgs.prototype = new ValidateEventArgs();

解决方案 »

  1.   

    个人观点:一和二的区别是:
    一:只有ValidateEventArgs方法被调用时,才扩展它的prototype
    二:js代码加载完,就扩展它的prototype
    关于ValidateEventArgs.prototype = new ValidateEventArgs(); 
    把ValidateEventArgs的prototype(原型)赋给一个ValidateEventArgs实例,
    其实这个实例还是调用ValidateEventArgs对象的prototype,所以我认为这样
    有点多余
      

  2.   

    把ValidateEventArgs的prototype(原型)被赋值为一个ValidateEventArgs实例,
      

  3.   

    问题1:
    两种方式产生结果是相同的,但是效率上会有一些细小的差别。
    比如新建两个ValidateEventArgs对象:var o1 = new ValidateEventArgs();
    var o2 = new ValidateEventArgs();  如果使用楼主的第一段代码,那么每一次新建对象ValidateEventArgs时,都会为ValidateEventArgs的prototype属性中的getResult方法重新赋值,比较浪费;
      如果使用第二段代码,那么无论你创建多少个实例对象,ValidateEventArgs构造函数的prototype都不会被更改,效率比较高(因为只有一次赋值操作而已)。问题2ValidateEventArgs.prototype = new ValidateEventArgs();不太清楚你为什么这么赋值,一般来说这种操作是Javascript内部的原型链继承方式,你可以通过把另外一个对象实例赋值给prototype的方式来继承那个对象的所有实例属性(就是那个对象的构造函数自己的prototype上的所有属性和方法),给你一个例子吧:// Base Class
    function BaseObject() {
    }
    BaseObject.prototype.baseProperty = "Base";// Sub Class
    function SubObject() {
    }
    SubObject.prototype = new BaseObject();
    SubObject.prototype.subProperty = "Sub";// test
    var sub = new SubObject();
    // see, SubObject inherit baseProperty property from
    // BaseObject
    alert(sub.baseProperty);
    Enjoy!!