2013-06-17 11 views
9

Dal hasOwnProperty presenta alcuni avvertimenti e svantaggi (finestra/uso esteso in ie8 problemi/ecc.).Vantaggio dell'utilizzo di Object.hasOwnProperty vs testing se Property is undefined

mi chiedevo se non v'è alcuna ragione di utilizzare anche ad esso, e se semplicemente testare se una proprietà non è definito è meglio giustificato & più semplicistico.

Ad esempio:

var obj = { a : 'here' }; 

if (obj.hasOwnProperty('a')) { /* do something */ } 

if (obj.a !== undefined) { /* do something */ } 
// or maybe (typeof (obj.a) !== 'undefined') 

Chiedo solo se qualcuno ha qualche buona intuizione su questo, preferirei essere utilizzando le più cross-browser amichevole, e fino a data di metodologia.

Ho visto anche questo prototipo over-scrittura per hasOwnProperty, che funziona, ma io non sono venduti su di esso di utilità ...

if (!Object.prototype.hasOwnProperty) { 
    Object.prototype.hasOwnProperty = function(prop) { 
     var proto = this.__proto__ || this.constructor.prototype; 
     return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]); 
    }; 
} 
+1

Qualcosa di diverso da utilizzare 'hasOwnProperty' è garantito per produrre falsi positivi o negativi – Xotic750

+0

se lo so Sto cercando una matrice o un oggetto o una funzione, la preferisco ancora più semplice: if (obj.a). Naturalmente, se obj.a può essere zero, "" o false, è necessario confrontarlo con! == undefined. inoltre, questo oggetto ha una "a" secondo ("a" in obj), ma non se (obj.a): {a: undefined} – dandavis

+1

Ulteriori informazioni: Potresti trovare interessante questo test jsPerf: http: // jsperf .com/hasOwnProperty-vs-in/2. In conclusione: '.hasOwnProperty' è ** molto ** più lento di qualsiasi altro modo di testare l'esistenza della proprietà (che è stato sorprendente per me TBH). –

risposta

3

Come ulteriori informazioni alla risposta fornita da @Pavel Gruba e al polyfil fornito. Per quanto ne so, non c'è un buon modo per polyfil hasOwnProperty per i browser che non lo supportano in modo nativo. Ne ho visti parecchi in natura e tutti producono falsi positivi o negativi. Se non ho assolutamente alternative, questo è ciò che ho creato per il mio uso, ma anche i falsi positivi e negativi. Secondo MSDN.

supportati nelle seguenti modalità di documenti: stranezze, Internet Explorer 6 standard, Internet Explorer 7 standard, Internet Explorer 8 standard, Internet Explorer 9 standard, Internet Explorer 10 standard. Supportato anche nelle app di Windows Store.

Javascript

function is(x, y) { 
    if (x === y) { 
     if (x === 0) { 
      return 1/x === 1/y; 
     } 

     return true; 
    } 

    var x1 = x, 
     y1 = y; 

    return x !== x1 && y !== y1; 
} 

function hasOwnProperty(object, property) { 
    var prototype; 

    return property in object && (!(property in (prototype = object.__proto__ || object.constructor.prototype)) || !is(object[property], prototype[property])); 
} 

function NewClass() {} 
NewClass.prototype = { 
    a: 'there' 
}; 

var obj = new NewClass(); 

if (obj.hasOwnProperty("a")) { 
    console.log("has property") 
} 

if (hasOwnProperty(obj, "a")) { 
    console.log("has property") 
} 

Su jsfiddle

12

Il metodo hasOwnProperty verifica che la proprietà è assegnato a opporsi direttamente . Quindi, se la proprietà 'a' è in prototipo, hasOwnProperty la filtrerà.

function NewClass() {} 
NewClass.prototype = { a: 'there' }; 
var obj = new NewClass(); 

if (obj.hasOwnProperty('a')) { /* code does not work */ } 
if (obj.a !== undefined) { /* code works */ } 

Quindi hasOwnProperty è più sicuro in molti casi.

+0

Molto vero ... Ho appena realizzato questo dopo postando la domanda! Sto avendo difficoltà a trovare il supporto del browser per hasOwnProperty, è almeno IE7 + compatibile? –

5

hasOwnProperty non controlla i valori non definiti verifica solo se la proprietà è assegnata all'oggetto, anche se non è definita

var obj = { a : undefined }; 
obj.hasOwnProperty("a") //true 
obj.a === undefined  //true 
obj.hasOwnProperty("b") //false 
obj.b === undefined  //true 
Problemi correlati