defineProperty inheritance VS defineProperties and create

# Andrea Giammarchi (12 years ago)

Another inconsistency just spotted in this (IMHO) funny way Object.defineProperty consider inherited properties for the descriptor, is that Object.defineProperties does not, so doesn't create.

I believe if there's a use case for recycled, inherited, descriptors, that's much more defineProperties/create rather than defineProperty.

Here a simple use case showing that this stuff is not consistent:

function Inherited() { return Inherited._singleton || ( Inherited._singleton = new Inherited ); } Inherited.prototype.test = {value: "test"};

Object.defineProperties({}, Inherited()).test; // udnefined

this will obviously work

function Forced(){ this.test = this.test; } Forced.prototype.test = {value: "test"};

Object.defineProperties({}, new Forced).test; //"test"

If we would like to reuse inheritance to create hierarchies ... as showed already, things are also broken.

function P(){} P.prototype.test = {value: "test"}; Object.create(null, new P).test; // undefined

Why Does This Matter Specially create, but defineProperties only, are mechanism used to define object properties in a more powerful way. These are also promoted as better way than simulated classical OOP in ES5

function enrich(base, current) { var self = Object.create(base), k; for (k in current) { self[k] = current[k]; } return self; }

var // Animal Descriptor Animal = enrich(null, { alive: { value: true } }), // Cat Descriptor Cat = enrich(Animal, { tail: { value: true } }) ;

// each Animal var generic = Object.create(null, Animal); var cat = Object.create(null, Cat);

generic.alive; // true cat.tail; // true cat.alive; // undefined

So, accordingly you find defineProperty consider inheritance a correct behavior in specs, what do you think about all other cases that are not behaving consistently or as expected?

Thanks for your attention.

br