我想利用visual studio intellisense,因此我读过:
http://msdn.microsoft.com/en-us/library/bb514138.aspx
无论如何为什么我没有得到intellisense:
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 for: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!!!!
}
});
答案 0 :(得分: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;
}
答案 1 :(得分: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 = foundCustomer
更改为c = new Customer(foundCustomer)
。我猜这可能触发了知识产权?