admin管理员组文章数量:1305793
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 badges1 Answer
Reset to default 13While 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.
本文标签: javascriptHow to retain prototype with angularcopy()Stack Overflow
版权声明:本文标题:javascript - How to retain prototype with angular.copy()? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741806004a2398508.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论