3

我想利用visual studio intellisense,因此我已阅读:

http://msdn.microsoft.com/en-us/library/bb514138.aspx

无论如何,为什么我没有得到智能感知:

function Customer() {
    this.Id = 0;
    this.FirstName = "";
    this.LastName = "";
}

function Test() {
    /// <returns type="Customer"></returns>

    var c = new Object();
    $.ajax({
        async: false,
        dataType: "json",
        url: "Ajax/GetCustomer.aspx",
        success: function (foundCustomer) {
            // I know that found customer is of type Customer
            c = foundCustomer;
        }
    });

    return c;
}

var x = Test();
x. // No intellicense! why?

我如何告诉 Visual Studio 知道该函数将返回 TYPE 的对象Customer?例如,如果我将函数 Test 替换为:function Test(){ return new Customer(); }然后 intellicense 将起作用。


编辑

我最后的目标是拥有类似的东西:

function Customer() {
    this.Id = 0;
    this.FirstName = "";
    this.LastName = "";
}

Object.prototype.CastToCustomer = function(){
    /// <returns type="Customer"></returns>
    return this;
}

$.ajax({
    async: false,
    dataType: "json",
    url: "Ajax/GetCustomer.aspx",
    success: function (foundCustomer) {

        foundCustomer = foundCustomer.CastToCustomer();
        foundCustomer.// Intellicense does not work :(
    }
});

我得到了很多 json 对象,我想使用这个辅助函数来转换它们。


临时解决方案:

这就是我最终做的事情:

function Customer() {
    this.Id = 0;
    this.FirstName = "";
    this.LastName = "";
}

$.ajax({
    async: false,
    dataType: "json",
    url: "Ajax/GetCustomer.aspx",
    success: function (foundCustomer) {
        // this will never be true on real browser. It is always true in visual studio (visual studio will now think that found customer is of type Customer ;)
        if (document.URL.length == 0) foundCustomer = new Customer();

        foundCustomer.// Intellisense works!!!!
    }
});
4

2 回答 2

2

您正在将返回值初始化为,Object因此它是 Intellisense 所基于的。如果将其初始化为空Customer,则 Intellisense 将检测到它正在返回一个Customer

function Test() {

    var c = new Customer(); //only for Intellisense

    $.ajax({...});

    return c;
}

Test(). //Customer members now appear

您还可以使用/// <param />来指定参数类型:

$.ajax({
    ...

        success: function (foundCustomer) {
           /// <param name='foundCustomer' type='Customer' />
           foundCustomer. //Customer members appear            
        }
});

最后,您的document.URL.length技巧也可以用于强制转换方法:

Object.prototype.CastToCustomer = function() {

  var c = new Customer();
  if (document.URL.length) c = this;
  return c;

}
于 2013-10-17T15:28:22.770 回答
0

如果您将 Customer 函数更改为接受参数:

function Customer(opts) {
    var opts = opts || {};

    this.id = 0;
    this.firstName = '';
    this.lastName = '';

    for (var i in opts) {
        if (opts.hasOwnProperty(i)) this[i] = opts[i];
    }
}

然后在您的Test函数中,更改c = foundCustomerc = new Customer(foundCustomer). 我猜这可能会触发智能?

于 2013-10-17T15:16:34.430 回答