0

我有一个js代码如下,

   function findDealerByIdResponse() {
findDealerByIdResponse.prototype = findDealerByIdResponseType;


this.getPrefix = function(){
        return "tns1";
};
this.getNS = function(){
    return "http://www.hp.com/bookservice";
};

} 

function findDealerByIdResponseType(){
var DEALER ;


this.getPrefix = function(){
        return "tns1";
};
this.getNS = function(){
    return "http://www.hp.com/bookservice";
};


}

function getName( obj ) { 

   var funcNameRegex = /function (.{1,})\(/;
   var results = new Object();
   results = (funcNameRegex).exec((obj).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};

function test(){
var req = new findDealerByIdResponse();
alert(getName(req));
}

但是,如果我第一次执行“测试”,它会给出我所期望的:“doTransactionType”。但之后它给出了 "Function" 。请说明原因。

谢谢

迪帕克

4

1 回答 1

0

After the first call to findDealerByIdResponse, you set its prototype property to a function, namely findDealerByIdResponseType. As a result, .constructor will be overwritten by this assignment, and it will resolve to the constructor of that function - which is, as any function, Function.

Instead, you want this:

// set prototype to a parent instance
findDealerByIdResponse.prototype = new findDealerByIdResponseType;

// restore .constructor
findDealerByIdResponse.prototype.constructor = findDealerByIdResponse;

You'd want to place it after the declarations of both functions.

于 2012-06-05T09:37:51.840 回答