2015-04-21 2 views
3

Я знаю, как петля печь объект I в 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 

Это не орфографическая ошибка так что не уверен, что происходит ..

Спасибо ..

+0

Проблема возникает в строке 51 после createObject.prototype.toString = .... for (key in objIn) { if (objIn.hasOwnProperty (key)) {// это вызывает ошибку. – Mani

ответ

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; 

} 

Я думаю, что это проблема.

1

Вы создаете это.resul t от объекта res, созданного с помощью Object.create(null) - в качестве прототипа используется null, поэтому он не имеет никаких начальных свойств. В конечном итоге вы назначаете некоторые свойства в инструкции

return res[test[0]] = test[1]; 

но hasOwnProperty не входит в их число. Вместо этого вы можете создавать пустые объекты с Object.create(Object).

И вы хотите использовать ту версию, которая не имеет key в кавычках:

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

Вы правы. – Mani

Смежные вопросы