Maheshjayachandran / closure-library

Automatically exported from code.google.com/p/closure-library
0 stars 0 forks source link

goog.inherits() does not clone arrays and objects #396

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago

What steps will reproduce the problem?

1. Run this code, which uses goog.inherits
var Person = function() {};
Person.prototype.m_array = [];
var Ninja = function() {};
goog.inherits( Ninja, Person );
var p = new Person();
var n = new Ninja();
p.m_array.push(123);
console.info( n.m_array ); 

2. Observe result in the debug console
Result is: "[123]"

What is the expected output? What do you see instead?
"[]"

What version of the product are you using? On what operating system?
Latest version of base.js, Chrome browser, OSX.

Please provide any additional information below.
It looks like the problem is caused by sharing prototypes and is probably not 
easy to fix.

Workaround:
var Ninja = function() { this.m_array = []; };
Or do you guys not consider this a bug at all?
Thx!

Original issue reported on code.google.com by bernd.pa...@gmail.com on 27 Nov 2011 at 9:02

GoogleCodeExporter commented 9 years ago
right, this is working as intended. All objects on the prototype are shared. I 
believe Closure Linter will warn you about this if you do it.

Original comment by Nicholas.J.Santos on 27 Nov 2011 at 9:44

GoogleCodeExporter commented 9 years ago
It sounds like you expect goog.inherits to copy members from one class to 
another (also known as mixins or composition-based inheritance).  That is not 
the case.  Closure uses true prototypal inheritance.  Anything on a superclass 
prototype is shared with all subclasses as well.  Closure style has a rule that 
only primitive values should be placed on the prototype chain.  Most often, the 
intention is to use an empty object/array as a default, but what ends up 
happening is exactly what you described:  methods end up mutating the prototype 
object instead of an instance-specific one.

Original comment by JayYoung...@gmail.com on 27 Nov 2011 at 9:50

GoogleCodeExporter commented 9 years ago
Thanks guys, I thought so too.

Best wishes,

- Bernd

Original comment by bernd.pa...@gmail.com on 28 Nov 2011 at 6:44