2012-01-12 51 views
1

我已经看到了网络下面的例子从一个WCF服务中获得一个JSON Product对象到JS:嵌套的原型来自jQuery的

function Product(ProductName, ProductDesc, Price, Quantity) { 
    this.ProductName = ProductName; 
    this.ProductDesc = ProductDesc; 
    this.Price = Price; 
    this.Quantity = Quantity; 
} 

function CallWCFService(WCFServiceURL) { 
    $.ajax({ 
     type: "GET", 
     url: WCFServiceURL, 
     contentType: "application/json; charset=utf-8", 
     dataType: 'json', 
     processdata: true, 
     success: function (msg) { 
      WCFServiceSucceeded(msg); 
     }, 
     error: WCFServiceFailed 
    }); 
} 

//On Successful WCF Service call 
function WCFServiceSucceeded(result) { 
    var productsArray = new Array(); 

    //Gets the Products 
    $.each(result, function (i, Product) { 
     productsArray[i]=Product; 
    }); 

    //Print all the product details 
    $.each(productsArray,function(i,Product) 
    { 
     alert(Product.ProductName + ' ' + Product.ProductDesc + ' ' + Product.Price + ' ' + Product.Quantity) 
    }); 
} 

(original source)

现在,我不能说什么是真的应该发生在这里(我的知识在JavaScript和jQuery中是可怕的小),但我可以说,我想了解这个片段,为了能够修改它以包含嵌套类型,即:而不是产品名称我们将拥有WCF服务响应中的列表属性及其自己的字段。

现在,具体地,在这个例子中,我不明白的地方被称为Product功能,它似乎是,它是在这里:

//Gets the Products 
    $.each(result, function (i, Product) { 
     productsArray[i]=Product; 
    }); 

但对我来说似乎是不清楚Product是否存在作为传递给$ .each的lambda的声明参数的行为,或者它是否实际调用了“构造函数”调用

您可以在此代码中指导我吗?

回答

3

Product功能不会被调用。事实上,如果没有它,代码就可以正常工作。发生什么情况是由WCF调用返回的JSON对象的格式或结构与Product类(由Product函数定义)完全相同。

each函数接受一个阵列和用于该阵列中的每个项目执行它提供的匿名函数。匿名函数有两个参数,iProducti是数组中项目的索引。 Product是在通过该项目的变量名。在这一点上,命名为Product的变量阴影的Product功能。

看来该项目已被转换为Product类的原因是因为所述对象具有相同的结构。