Pergunta

When I have an array like var user = { name : 'Bob'}; what is the difference when using the following instruction?

localuser = user.name;
localuser = 'name' in user ? user.name : 'bob';
localuser = user.hasOwnProperty('name') ? user.name : 'bob'
Foi útil?

Solução

Example:

var o = { 'foo': 'bar' };

console.log('constructor' in o); // TRUE
console.log('foo' in o); // TRUE

console.log(o.hasOwnProperty('constructor')); // FALSE
console.log(o.hasOwnProperty('foo')); // TRUE

hasOwnProperty

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

in

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

The in operator returns true if the specified property is in the specified object.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top