22

誰でも私を啓発できますか、との違いは何 hasOwnPropertyですかpropertyIsEnumerable:

function f(){
  this.a = 1;
  this.b = 2;
  this.c = function(){}
}
f.prototype = {
  d : 3,
  e : 4,
  g : function(){}
}

//creating the instance of an object:
var o = new f();

//And here I can't see difference.
//In my opinion they are doing the same thing
console.log("o.hasOwnProperty('a'):", o.hasOwnProperty('a')); //true
console.log("o.hasOwnProperty('b'):", o.hasOwnProperty('b')); //true
console.log("o.hasOwnProperty('c'):", o.hasOwnProperty('c')); //true
console.log("o.hasOwnProperty('d'):", o.hasOwnProperty('d')); //false
console.log("o.hasOwnProperty('e'):", o.hasOwnProperty('e')); //false
console.log("o.hasOwnProperty('g'):", o.hasOwnProperty('g')); //false

console.log("o.propertyIsEnumerable('a')", o.propertyIsEnumerable('a')); //true
console.log("o.propertyIsEnumerable('b')", o.propertyIsEnumerable('b')); //true
console.log("o.propertyIsEnumerable('c')", o.propertyIsEnumerable('c')); //true
console.log("o.propertyIsEnumerable('d')", o.propertyIsEnumerable('d')); //false
console.log("o.propertyIsEnumerable('e')", o.propertyIsEnumerable('e')); //false
console.log("o.propertyIsEnumerable('g')", o.propertyIsEnumerable('g')); //false

間違っていたら訂正して

4

4 に答える 4

32

true「propertyIsEnumerable」関数は、「hasOwnProperty」に対して返されないプロパティを常に除外します。プロパティを列挙できないようにするために何もしていないので、テストでは結果は同じです。

「defineProperty」を使用して、列挙できないプロパティを定義できます。MDN でこのリファレンスを参照してください。

Object.defineProperty(obj, "hideMe", { value: null, enumerable: false });

それは次のようなものです:

obj.hideMe = null;

ただし、プロパティはfor ... inループに表示されず、 を使用したテストはpropertyIsEnumerableを返しfalseます。

このトピック全体は、古いブラウザーでは利用できない機能に関するものです。

于 2012-06-10T13:10:16.827 に答える
30

hasOwnPropertytrue列挙不可能な「独自の」プロパティ(のようlengthに)でも返されArrayます。列挙可能な「独自の」プロパティに対してのみpropertyIsEnumerable返されます。(「列挙可能な」プロパティは、ループなどで表示されるプロパティです。)truefor..in

例:

var a = [];
console.log(a.hasOwnProperty('length'));       // "true"
console.log(a.propertyIsEnumerable('length')); // "false"

または非配列オブジェクトを使用:

var o = {};
Object.defineProperty(o, "foo", { enumerable: false });
console.log(o.hasOwnProperty('foo'));       // "true"
console.log(o.propertyIsEnumerable('foo')); // "false"

( を使用するObject.definePropertyと、enumerableデフォルトはになりますfalseが、わかりやすくするために上記で明示しています。)

于 2012-06-10T13:22:28.893 に答える
4

違いは、propertyIsEnumerable は、プロパティが存在する場合にのみ true を返し、プロパティで ForIn を実行できる場合、ForIn サポートに関係なくプロパティが存在する場合、hasOwnProperty は true を返すことです。

MSDN から:

proName が object に存在し、ForIn ループを使用して列挙できる場合、propertyIsEnumerable メソッドは true を返します。指定された名前のプロパティが object にない場合、または指定されたプロパティが列挙可能でない場合、propertyIsEnumerable メソッドは false を返します。通常、定義済みのプロパティは列挙可能ではありませんが、ユーザー定義のプロパティは常に列挙可能です。

hasOwnProperty メソッドは、オブジェクトが指定された名前のプロパティを持っている場合は true を返し、そうでない場合は false を返します。このメソッドは、プロパティがオブジェクトのプロトタイプ チェーンに存在するかどうかをチェックしません。プロパティは、オブジェクト自体のメンバーである必要があります。

于 2012-06-10T13:10:43.963 に答える