在原型中循环遍历一个对象

3
我知道如何在JavaScript中遍历一个对象。但当我尝试在对象的原型中执行此操作时,出现“undefined is not a function”的错误。我的代码如下:

var createObject = function(strIn) {
  this.result = strIn;
}

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];
  });
  this.result = res;
  res = Object.create(null);
  return this.result;

}

createObject.prototype.toString = function() {
  //{ jake: 'dog', finn: 'human' }
  //"jake=dog&finn=human"
  var key,
    objIn = Object.create(null),
    returnresult = '';
  objIn = this.result; //this is causing issue
  console.log('obj', objIn);
  console.log(typeof(objIn))
  for (key in objIn) {
    console.log(objIn.hasOwnProperty('key')) //trying to see wht this results in ::GIVES 'undefined is not a function error'
      //     if(objIn.hasOwnProperty(key)){
      //       returnresult += key+'='+objIn[key]+'&'
      //     }
  }
  this.result = returnresult;
  returnresult = Object.create(null);
  return this.result;
}


var test = new createObject('jake=dog&finn=human');

console.log(test);
console.log(test.toObject())
console.log(test);
console.log(test.toString());
console.log(test);

以下是结果和错误信息:
{ result: 'jake=dog&finn=human' } 
{ jake: 'dog', finn: 'human' } 
{ result: { jake: 'dog', finn: 'human' } } 
obj { jake: 'dog', finn: 'human' } 
object 
solution.js:52 
    console.log(objIn.hasOwnProperty('key')  ) 
                      ^ 
TypeError: undefined is not a function 
    at createObject.toString (solution.js:52:23) 
    at solution.js:68:18 

这不是拼写错误,所以不确定发生了什么情况...

谢谢...


问题出在第51行,即在createObject.prototype.toString = ....之后。for (key in objIn){if(objIn.hasOwnProperty(key)){//这是导致错误的原因。 - Mani
2个回答

1
你正在创建这个.result属性,基于使用Object.create(null)创建的res对象 - 它使用null作为原型,因此它没有任何初始属性。你最终会在语句中分配一些属性。
return res[test[0]] = test[1];

但是 hasOwnProperty 不在其中。您可以使用 Object.create(Object) 创建空对象代替。
并且您想使用不带引号的 key 版本:
  //     if(objIn.hasOwnProperty(key)){

1

对象是引用类型。

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

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

所以:
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;

}

我认为这就是问题所在。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接