最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to retain prototype with angular.copy()? - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Feb 3, 2015 at 18:35 JohannJohann 4,3733 gold badges42 silver badges41 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

While the ment in the mit 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.

发布评论

评论列表(0)

  1. 暂无评论