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 105 106
| { /*
* Problème : copier un objet qui utilise "super".
*
* Un objet qui utilise "super" est fermement
* connecté avec son objet d'origine.
*
* Il n'y a actuellement aucun moyen pour cloner
* un tel objet.
*
* Exemple :
*/
const
kCloneObject = function( originalObject ){
if ( ( typeof originalObject !== 'object' ) || originalObject === null ){
throw new TypeError( "originalObject parameter must be an object which is not null" );
}
function deepProto( originalObject ){
let deepCopy = Object.create( Object.getPrototypeOf( originalObject ) );
for ( let attribute in originalObject ){
deepCopy[ attribute ] = originalObject[ attribute ];
if ( typeof originalObject[ attribute ] === 'object' && originalObject[ attribute ] !== null ){
deepCopy[ attribute ] = deepProto( originalObject[ attribute ] );
}
}
return deepCopy;
}
return deepProto( originalObject );
},
kFirstName = new WeakMap(),
kLastName = new WeakMap(),
kFirstNameType = 'string',
kLastNameType = 'string',
kSetPerson = function( obj, first, last ){
if ( kGetType( first ) === kFirstNameType && kGetType( last ) === kLastNameType ){
kFirstName.set( obj, first );
kLastName.set( obj, last );
} else {
throw `Type des paramètres incompatibles.
first : ${ kFirstNameType } attendu,
last : ${ kLastNameType } attendu`;
}
return obj;
},
kPays = Symbol( 'Pays' ),
kPaysType = 'string',
kSetPays = function( obj, value ){
if ( kGetType( value ) === kPaysType ){
obj[ kPays ] = value;
} else {
throw `Type des paramètres incompatibles.
pays : ${ kPaysType } attendu`;
}
return obj;
},
Person = class {
constructor( first, last ){
kSetPerson( this, first, last );
}
get firstName( ){
return kFirstName.get( this );
}
get lastName( ){
return kLastName.get( this );
}
fullName( ){
return kFirstName.get( this ) + " " + kLastName.get( this );
}
},
Employee = class extends Person {
constructor( prenom, nom, pays ){
super( prenom, nom );
kSetPays( this, pays );
}
get pays( ){
return this[ kPays ];
}
set pays( value ){
kSetPays( this, value );
}
};
let
ObjMoi = new Employee( 'Daniel', 'Hagnoul', 'Belgique' ),
cloneObjMoi = kCloneObject( ObjMoi );
console.log( "ObjMoi = ", ObjMoi, ObjMoi.fullName() );
console.log( "cloneObjMoi = ", cloneObjMoi, cloneObjMoi.fullName() );
/*
* ObjMoi = Object {Symbol(Pays): "Belgique"} Daniel Hagnoul
* cloneObjMoi = Object {} undefined undefined
*/
} |