2015-06-03 20 views
18

sto leggendo il MDN javascript reference, di conseguenza il seguente codice non restituisce più false:Qual è lo scopo di consentire nomi di proprietà duplicati?

function haveES6DuplicatePropertySemantics(){ 
    "use strict"; 
    try { 
    ({ prop: 1, prop: 2 }); 

    // No error thrown, duplicate property names allowed in strict mode 
    return true; 
    } catch (e) { 
    // Error thrown, duplicates prohibited in strict mode 
    return false; 
    } 
} 

In ECMAScript 5 strict mode code, duplicate property names were considered a SyntaxError. With the introduction of computed property names making duplication possible at runtime, ECMAScript 6 has removed this restriction.

La mia domanda è, quali sono i vantaggi pratici di permettere struttura a nomi duplicati nei inizializzatori? Posso vedere come, quando le proprietà dell'oggetto vengono assegnate dinamicamente, a volte ciò potrebbe accadere, ma poiché l'ordine di precedenza determina apparentemente quale delle proprietà è effettivamente impostata sull'oggetto appena creato - questo sembra più che qualcosa di simile a un comportamento indefinito che è meglio evitare.

+0

genera un errore per me su cromo v40 'SyntaxError Uncaught: proprietà data duplicata nell'oggetto letterale non ammessi in stretta mode' ma non e 'colto da' try..catch' – Xotic750

+1

Esso restituisce 'true' per me su chromium v42/firefox 37, potrebbe richiedere il flag "Experimental JavaScript features" per ottenere il comportamento equivalente su v40? – user3467349

+0

Si desidera eseguire lo script in ES6 (sperimentale) o ES5? Chromium v42 e firefox 37 ora funzionano come standard in modalità ES6? – Xotic750

risposta

15

what are the practical benefits of allowing duplicate property-names in the initializers

Non ci sono vantaggi pratici in quanto tali. Ora che ci sono chiavi di proprietà calcolate in ECMA Script 6, il valore effettivo delle chiavi sarà determinato solo al runtime. Così com'è, le chiavi possono essere aggiunte agli oggetti in fase di esecuzione e sovrascrivono la chiave e il valore esistenti. Lo stesso comportamento è esteso in ES-6 e la restrizione di non consentire il controllo delle chiavi duplicate del tempo di compilazione viene rimossa.

Citando Allen Wirfs-Brock dalla discussion in ESDiscuss Mailing list,

The plan has been that runtime validation would be performed for any object literals containing computed property keys and the current spec. draft contains pseudo code for doing the checks. However a bug report (https://bugs.ecmascript.org/show_bug.cgi?id=1863 ) points out an issue with the current spec. For example, the current spec. throws an error on:

({get a() {}, 
    get ["a"]() {} 
}); 

but not on:

({get ["a"]() {}, 
    get a() {} 
}); 

Basically, it isn't sufficient to only check for an already defined property key when processing property definitions that contains a computed key. If any computed keys exist the checking has to be done even for the definitions that have literal property names. And it isn't sufficient to just consider the property keys and the data/accessor property distinction, the validation also has to take into account the syntactic form of the definition and whether or not strict mode applies..

It turns out that even in pseudo code, this is a fairly complicated set of runtime validation rules to apply. I'm having a hard time convincing myself that the runtime computational and meta data costs of this dynamic validation is justified. It costs too much and the actual benefit is pretty small.

For that reason, I propose that we drop this runtime validation of object literals (and class definition). We would still have the static validation and early errors for property definitions that don't have computed keys. But anything that makes it past those checks (including all property definitions with computed names) are just processed sequentially with no duplicate name checking.

Quindi, la proposta è stato quello di mantenere il controllo di tempo di compilazione per i tasti normali e as per this comment l'assegno è stata abbandonata in seguito. In Revision 26,

Eliminated duplicate property name restrictions on object literals and class definitions

+1

Quindi pensi che sia troppo difficile codificare un controllo del tempo di compilazione, per mantenere le regole "rigide" definite in ES5 ed era più facile rendere "rigoroso" meno "rigoroso" il rispetto delle chiavi di proprietà calcolate ES6. O è effettivamente scritto nella specifica ES6 corrente che deve essere eliminato, non riesco a trovare una risposta nelle specifiche? – Xotic750

+0

@ Xotic750 È menzionato in [Allegato E] (http://people.mozilla.org/~jorendorff/es6-draft.html#sec-additions-and-changes-that-introduce-incompatibility-with-prioreditions) - 'In ECMAScript 2015, non è più un errore precoce avere nomi di proprietà duplicati in Inizializzatori oggetti. – thefourtheye

+0

Ok, grazie per avermi indirizzato al riferimento. A me sembra strano rimuovere un errore così precoce. Non capisco il ragionamento alla base, oltre alle possibili difficoltà di codifica. – Xotic750