Javascript 在原型中的对象上循环

Javascript 在原型中的对象上循环,javascript,prototype,Javascript,Prototype,我知道如何在javascript中循环对象I。 但当我试图在一个对象的原型中这样做时,我得到了“未定义不是函数”的错误。我的代码如下 var createObject=函数(strIn){ 这个结果=strIn; } createObject.prototype.toObject=函数(){ var objData=this.result.split('&'); this.result=Object.create(null);//{ var res=Object.create(空); forE

我知道如何在javascript中循环对象I。 但当我试图在一个对象的原型中这样做时,我得到了“未定义不是函数”的错误。我的代码如下

var createObject=函数(strIn){
这个结果=strIn;
}
createObject.prototype.toObject=函数(){
var objData=this.result.split('&');
this.result=Object.create(null);//{
var res=Object.create(空);
forEach(函数(值、索引){
var测试=值。拆分('='))
返回res[test[0]]=test[1];
});
这个结果=res;
res=Object.create(空);
返回此结果;
}
createObject.prototype.toString=函数(){
//{杰克:'狗',芬恩:'人'}
//“杰克=狗,芬恩=人”
var键,
objIn=Object.create(null),
returnresult='';
objIn=this.result;//这是导致问题的原因
console.log('obj',objIn);
控制台日志(类型(objIn))
for(输入objIn){
console.log(objIn.hasOwnProperty('key'))//尝试查看这会导致什么::GIVES“未定义不是函数错误”
//if(objIn.hasOwnProperty(键)){
//returnresult+=key+'='+objIn[key]+'&'
//     }
}
this.result=返回结果;
returnresult=Object.create(空);
返回此结果;
}
var test=newcreateobject('jake=dog&finn=human');
控制台日志(测试);
console.log(test.toObject())
控制台日志(测试);
log(test.toString());

控制台日志(测试)
您正在创建这个。result是由
res
对象生成的,该对象是用
对象创建的。create(null)
-它使用
null
作为原型,因此它没有任何初始属性。最后在语句中指定一些属性

return res[test[0]] = test[1];
但hasOwnProperty不在其中。您可以使用
对象创建空对象。请改为创建(对象)

您希望使用引号中没有
键的版本:

  //     if(objIn.hasOwnProperty(key)){

对象是引用类型

Object.create(null)
返回没有原型的真正空对象。例如:

var emptyObj = Object.create(null)
emptyObj.hasOwnProperty // Return undefined.
emptyObj.prototype // Return undefined.
因此:


我认为这就是问题所在。

问题在createObject.prototype.toString=….之后的第51行。。。。for(key in objIn){if(objIn.hasOwnProperty(key)){//这会导致错误。
createObject.prototype.toObject = function() {
  var objData = this.result.split('&');
  this.result = Object.create(null); //{}
  var res = Object.create(null);
  objData.forEach(function(value, index) {
    var test = value.split('=')
    return res[test[0]] = test[1];
  });

  // Here you say - this.result = res
  // But it's reference type, so the address of this variable will be
  // Setted to `this`
  this.result = res;

  // here you change the reference value of res.
  // so this.result will be = Object.create(null) after next line exec.
  res = Object.create(null);

  return this.result;

}