简体   繁体   中英

Javascript object changing automatically?

I have the following code:

var doneFile=convertToMOSTEM(curFile.file,curFile.color,curFile.importance);
console.log('doneFile:');
console.log(doneFile);
debugger;
filesOS.add(doneFile);
debugger;

convertToMOSTEM returns a custom object. The console.log logs the custom object created by convertToMOSTEM to the console, but at the debugger statement directly after the console.log logs it as a different object. I do not wish to elaborate more about the contents of convertToMOSTEM , and am instead asking for situations where this can happen. I can say, however, that convertToMOSTEM creates a custom object with a custom constructor, and then it modifies some of the properties of that custom object, then returns the modified object. The console.log logs the correct version of the object, but the object that I get in the debugger statement is like a clean version of the custom object without the extra modifications applied by the convertToMOSTEM function. I am not sure if that is very clear, if you have any questions please ask me questions in the comments.

One possibility is that you're being misled by one bit of behavior that console.log() has that isn't obvious.

When you log an object, the console doesn't save all of the properties of that object for display later. The only real-time display is whatever the single-line printout from console.log() shows. If you click the triangle to expand an object that was displayed with console.log() , the expanded display shows the properties of that object at the time you click the triangle , not at the time of the original console.log() call.

To avoid this, log the individual properties you are interested in at the time of making the call. For example, if you have a person object with id , name , and email properties, don't do this:

console.log( person );

Do this instead:

console.log( person.id, person.name, person.email );

That way, if those three properties are string values, you will log their actual values at the time you make the console.log() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM