オブジェクトがプロパティを持っているか、確認する方法
JavaScriptで、対象のオブジェクトが指定したプロパティを保持しているかを、確認する方法を、メモとして残しておく。
var Person = function(name, age){ this.name = name; this.age = age; }; Person.prototype.animal = "Yes!"; var emi = new Person("emi", 21); // in演算子を使うと、プロトタイプが保持ているプロパティまで参照する console.log("name" in emi) // true console.log("animal" in emi) // true // hasOwnProperty(key)では、プロトタイプまで参照しない console.log(emi.hasOwnProperty('age')) // true console.log(emi.hasOwnProperty('animal')) // false