我知道如何在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
这不是拼写错误,所以不确定发生了什么情况...
谢谢...