解决此问题的常用方法是为您的 Object( cData) 提供一个静态工厂方法,该方法将接受 DTO ( Data Transfer Object ) 并返回一个新cData实例,即:
function cData() { 
    this.Email = "";
    this.Name = "";
    this.test = function () {
        alert("lol");
    }
}
// Static factory which produces a new `cData` object from the supplied
// Data Transfer Object.  Note this function belongs to the Constructor
// function rather than instances created when it's used.
cData.fromDTO(value) {
        // Create a new cData instance.
        var result = new cData();
        // Copy the properties from the DTO.
        result.Email = value.Email;
        result.Name = value.Name;
        // Return the populated instance.
        return result;
}
然后您可以使用静态工厂来处理 AJAX 调用的结果,即:
function onAjaxResponse(response) {
    var myData = cData.fromDTO(JSON.parse(response));
    // Invoke the 'test' method.
    myData.test();
}
这也在数据传输层(来自服务器的数据)和您的业务逻辑(您的 JavaScript 应用程序)之间提供了清晰的分离;如果您需要更改 DTO 的属性(例如:Name更改为FirstName),那么您只需在一处修改代码(fromDTO工厂方法)。
作为旁注,您应该考虑在命名构造函数时使用 BumpyCaps(即:第一个字符应该是大写的,即:MyClass而不是myClass像任何其他函数那样)。