I am using Angular.js 1.3.x. In previous versions of Angular (including 1.3.0-beta5), the following code would copy the properties from the prototype directly to the new object:
function x() {};
x.prototype.logIt = function() {console.log("it")};
var src = new x(); // x has custom properties on the prototype
var dest = {};
angular.copy(src, dest);
dest.logIt(); // "TypeError" in Angular 1.3.0+
However, in Angular.js 1.3.0+, the properties from the prototype are totally lost, despite the fact that the migration guide for 1.2 to 1.3 says:
This changes angular.copy so that it applies the prototype of the original object to the copied object. Previously, angular.copy would copy properties of the original object's prototype chain directly onto the copied object.
How do I keep the properties from the prototype?
While the comment in the commit linked to from the migration guide says:
This changes
angular.copy
so that it applies the prototype of the original object to the copied object.
this is only true when the destination argument to angular.copy(source, [destination]);
is not provided. When destination
is provided, only the direct properties of the object are copied.
The solution is to provide only the source
object to the angular.copy
function, leaving off the destination
parameter:
function x() {};
x.prototype.logIt = function() {console.log("it")};
var src = new x();
var dest = angular.copy(src); // no second parameter
dest.logIt(); // logs "it"
Update: This appears to still be relevant, as angular.copy
in v1.6.5 only calls getPrototypeOf(source)
if destination is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With