Improve the Node version of Base.isPlainObject()

This commit is contained in:
Jürg Lehni 2013-05-09 15:30:18 -07:00
parent 1e9b3a630c
commit 82b9cb3dbf

View file

@ -90,18 +90,19 @@ context.include('paper.js');
// Fix version now. Remove 2nd dot, so we can make a float out of it: // Fix version now. Remove 2nd dot, so we can make a float out of it:
options.version = parseFloat(json.version.replace(/(.)(\d)$/, '$2')); options.version = parseFloat(json.version.replace(/(.)(\d)$/, '$2'));
// Since the created context fo Paper.js compilation, and the context in which // Since the context used for Paper.js compilation, and the context in which
// Node.js scripts are executed do not share the definition of Object and Array, // Node.js scripts are executed do not share the definition of Object, we need
// we need to redefine Base.isPlainObject() here. // to redefine Base.isPlainObject() here.
// Object(obj) === obj is a trick from underscore, but also returns true for all // So instead of checking for Object.prototype, we're checking
// Base objects. So we are filtering these out with an instanceof check, but // proto.constructor.name for 'Object'
// Include Base instances since we're using them as hashes.
// TODO: Benchmark the speed and consider this implementation instead of the // TODO: Benchmark the speed and consider this implementation instead of the
// current one. // current one in straps.js too
var Base = context.Base; var Base = context.Base;
Base.isPlainObject = function(obj) { Base.isPlainObject = function(obj) {
return Object(obj) === obj && !Array.isArray(obj) && (!(obj instanceof Base) var proto = obj !== null && typeof obj === 'object'
|| Object.getPrototypeOf(obj) === Base.prototype); && Object.getPrototypeOf(obj);
return proto && (proto.constructor.name === 'Object'
|| proto === Base.prototype);
}; };
// Expose the Canvas, XMLSerializer to paper scopes: // Expose the Canvas, XMLSerializer to paper scopes: