0

While playing around with some pet projects today, I came around a certain peculiarity that I can't quite explain. Here's a log from a node repl:

> foo = Object.create({}, { toString: { value: function() { return 'bob' } } })
{}
> bar = Object.create(foo)
{}
> bar.toString()
'bob'
> bar.hasOwnProperty('toString')
false
> bar.toString = function() { return 'nope' }
[Function]
> bar.toString()
'bob'

It was my expectation that bar.toString would shadow foo.toString, however this does not seem to happen. Setting the toString property to writable: true when creating foo makes it work as I'd expected.

Can prototype properties that aren't writable be shadowed?

Marcus Stade
  • 4,724
  • 3
  • 33
  • 54
  • clarity: it's useful to note that any property name does the same, "toString2" or "myProp", not just "toString" – dandavis Feb 08 '15 at 00:56
  • The main issue here is the same as this question: [Creating new objects from frozen parent objects](http://stackoverflow.com/questions/19698533/creating-new-objects-from-frozen-parent-objects) – Qantas 94 Heavy Feb 08 '15 at 02:57
  • @Qantas94Heavy is right, this question should be closed as a duplicate. Thanks for the link! – Marcus Stade Feb 08 '15 at 15:13

1 Answers1

0

Yes, you can use Object.defineProperty:

Object.defineProperty(bar, 'toString', {
    configurable: true, // optional
    writable: true,     // optional
    value: function() { return 'nope'; }
});
Oriol
  • 274,082
  • 63
  • 437
  • 513