相关疑难解决方法(0)

如何检查对象是否在JavaScript中具有属性?

如何检查对象是否在JavaScript中具有属性?

考虑:

x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
    //Do this
}
Run Code Online (Sandbox Code Playgroud)

这是最好的方法吗?

javascript

1396
推荐指数
20
解决办法
90万
查看次数

hasOwnProperty vs propertyIsEnumerable

任何人都可以启发我,hasOwnProperty和propertyIsEnumerable有什么区别:

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

创建对象的实例:

var o = new f();
Run Code Online (Sandbox Code Playgroud)

在这里,我看不出差异.在我看来,他们正在做同样的事情

o.hasOwnProperty('a'); //true
o.hasOwnProperty('b'); //true
o.hasOwnProperty('c'); //true
o.hasOwnProperty('d'); //false
o.hasOwnProperty('e'); //false
o.hasOwnProperty('g'); //false

o.propertyIsEnumerable('a'); //true
o.propertyIsEnumerable('b'); //true
o.propertyIsEnumerable('c'); //true
o.propertyIsEnumerable('d'); //false
o.propertyIsEnumerable('e'); //false
o.propertyIsEnumerable('g'); //false
Run Code Online (Sandbox Code Playgroud)

如果我错了,请找我

javascript prototype

20
推荐指数
3
解决办法
6483
查看次数

标签 统计

javascript ×2

prototype ×1