This repository has been archived by the owner on Dec 28, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nano-clone.js
104 lines (84 loc) · 3.03 KB
/
nano-clone.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
(function(){'use strict';
/**
* @version v1.0.0-alpha
* @author Alex Shvets
* @see www.github.com/quadroid/clonejs-nano
*/
function clone(/** !Object|Function */proto, /** !ObjLiteral= */ownProperties,
/** function=(clone.byProto||clone.byObjectCreate||clone.byConstructor) */cloneBy
){
if('function' === typeof proto){
proto = proto.prototype;
}
if( ownProperties === undefined){
ownProperties = {};
}
if( cloneBy === undefined){
cloneBy = _cloneMode;
}
//<//arguments>
if('function' === typeof proto.$clone){
return proto.$clone( ownProperties );
}else{
return cloneBy( proto, ownProperties);
}
}
/// clone modes:
function byProto(/** !Object */obj, /** !ObjLiteral */ownProperties){
ownProperties.__proto__ = obj;
return ownProperties;
}
function byObjectCreate(/** !Object */obj, /** !ObjLiteral */ownProperties){
var newObj = Object.create(obj);
for( var key in ownProperties ) {
var pd = Object.getOwnPropertyDescriptor( ownProperties, key ) // if we use new[key]=own[key], then get/set accessors of own are lost
pd.set || pd.get ? Object.defineProperty( newObj, key, pd ) : newObj[key] = ownProperties[key]; // but via defineProperty they are copied
}
return newObj;
}
function byConstructor(/** !Object */proto, /** ObjLiteral= */ownProperties){
function _Clone(ownProperties){
for(var key in ownProperties) this[key] = ownProperties[key];
}
_Clone.prototype = proto;
// Save custom constructor for public
if(!proto.hasOwnProperty('constructor') ){
proto.constructor = _Clone;
}
/**
* Save custom constructor in closure of $clone method.
* @override */
proto.$clone = function(ownProperties){
return new _Clone(ownProperties);
}
return new _Clone(ownProperties);
}
/// Select clone mode
if('__proto__' in {}){
clone.byProto = byProto;
}
if( typeof Object.create === 'function' ){
clone.byObjectCreate = byObjectCreate;
}
clone.byConstructor = byConstructor;
var _cloneMode = clone.byProto || clone.byObjectCreate || clone.byConstructor;
// // // // // // // // // // // // // // // // // // // // // // // // // // // //
// CommonJS modules (node.js)
if(typeof module === 'object' && 'exports' in module){
module.exports = clone;
// AMD (require.js)
}if(typeof define === 'function'){
define(function(){return clone});
// Browser
}else{
var _oldClone = window.clone;
window.clone = clone;
/**
* Replaces `window.clone` by previous value.
* @returns {clone} function */
clone.noConflict = function(){
window.clone = _oldClone;
return clone;
}
}
})();