1

I'm writting a small library in node and i have found some interesting behaviors. When i try these code on cmd:

Object.prototype.set = function (a) { this.a = a };
let obj = {};
obj.set(6);
obj

It returns: { a: [Setter] }

I try to type obj.a and then it returns correctly 6. When i check it on browser it still runs normally without any problem:

Object.prototype.set = function (a) { this.a = a };
let obj = {};
obj.set(6);
obj
// => { a: 6 }

So i wonder what has happened with node. Is this some kind of side effect? Should i care about it and should i put these code into my library? Thanks!

P/s: I'm using node version 7.7.3

Clite Tailor
  • 438
  • 5
  • 14
  • Setter could be something like a Generator / Iterator, due to which as soon as it is accessed, it returns a value? This might be something introduced in ES6 and I'm waiting for an answer too. – Ananth Apr 09 '17 at 17:24
  • You may want to note that it's generally considered an anti-pattern to add non-standard methods to built-in object prototypes. Besides the opportunity for conflict with other add-on libraries, it can mess up other code that gets confused when enumerable things show up in places they aren't supposed to be. For example, a simple `for (x in obj)` loop will now show the `set` property. – jfriend00 Apr 09 '17 at 17:33
  • I don't worry about that, i use `Object.defineProperty` and use it only for `Object.prototype`. it is predictable (at least when someone use my lib). i'm just wondering whether this is a bad behavior and it may lead to other serious problems! :/ – Clite Tailor Apr 10 '17 at 06:38
  • Oh, i've just checked. `Object.defineProperty` cannot define `set` property because there is `value` inside `descriptor`! [Wrong behavior in Google Chrome](http://stackoverflow.com/questions/19349309/wrong-behaviour-in-google-chrome-object-defineproperty) – Clite Tailor Apr 10 '17 at 07:08

0 Answers0