Skip to content

Commit

Permalink
fix(client): Fix stringify serializing objects
Browse files Browse the repository at this point in the history
Serialize uses the name of the constructor to serialize objects.
When the object was created using Object.create(null) or has a property
constructor this may throw an Error
  • Loading branch information
jakzale committed Jul 18, 2014
1 parent 51f1b88 commit 0d0972a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
9 changes: 7 additions & 2 deletions client/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,16 @@ var stringify = function stringify(obj, depth) {
} else if (obj.outerHTML) {
return obj.outerHTML;
} else {
strs.push(obj.constructor.name);
var constructor = 'Object';
if (obj.constructor && typeof obj.constructor === 'function') {
constructor = obj.constructor.name;
}

strs.push(constructor);
strs.push('{');
var first = true;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (first) {
first = false;
} else {
Expand Down
22 changes: 22 additions & 0 deletions test/client/stringify.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,28 @@ describe('stringify', function() {
expect(stringify(['a', 'b', null, true, false])).toBe("['a', 'b', null, true, false]");
});

it('should serialize objects', function () {
var obj;


obj = {a: 'a', b: 'b', c: null, d: true, e: false};
expect(stringify(obj)).toBe('Object{a: \'a\', b: \'b\', c: null, d: true, e: false}');

function MyObj() {
this.a = 'a';
}

obj = new MyObj();
expect(stringify(obj)).toBe('MyObj{a: \'a\'}');

obj = {constructor: null};
expect(stringify(obj)).toBe('Object{constructor: null}');

obj = Object.create(null);
obj.a = 'a';
expect(stringify(obj)).toBe('Object{a: \'a\'}');
});


it('should serialize html', function() {
var div = document.createElement('div');
Expand Down

0 comments on commit 0d0972a

Please sign in to comment.