JavaScript 对象构造函数未显示稳定的值

JavaScript Object constructor not showing stable value

本文关键字:显示 对象 构造函数 JavaScript      更新时间:2023-09-26

我有一个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"。但之后它给出了"功能"。请解释原因。

谢谢

迪帕克

在第一次调用 findDealerByIdResponse 之后,你将其 prototype 属性设置为一个函数,即 findDealerByIdResponseType 。结果,.constructor将被此赋值覆盖,它将解析为该函数的构造函数 - 与任何函数一样,该构造函数Function .

相反,您需要以下内容:

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

您希望将其放在两个函数的声明之后。