LoginSignup
109
73

More than 5 years have passed since last update.

in と hasOwnProperty() の違い

Last updated at Posted at 2012-07-27

基本的なことですが in を知らなかったので。両方ともオブジェクトのプロパティの有無を返しますが、in は prototype チェーンをさかのぼる一方、hasOwnProperty() はさかのぼりません。

function Foo() {
  this.foo = 'Foo!';
}
function Bar() {
  this.bar = 'Bar!';
}
Foo.prototype = new Bar();
Bar.prototype.baz = 'Baz!';

var obj = new Foo();

console.log('foo' in obj); // true
console.log('bar' in obj); // true
console.log('baz' in obj); // true

console.log(obj.hasOwnProperty('foo')); // true
console.log(obj.hasOwnProperty('bar')); // false
console.log(obj.hasOwnProperty('baz')); // false
109
73
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
109
73