JavaScript中hasOwnProperty函数方法是返回一个布尔值,指出一个对象是否具有指定名称的属性。 使用方法:
object.hasOwnProperty(proName)
其中参数object是必选项。一个对象的实例。
proName是必选项。一个属性名称的字符串值。
如果 object 具有指定名称的属性,那么JavaScript中hasOwnProperty函数方法返回 true;反之则返回 false。此方法无法检查该对象的原型链中是否具有该属性;该属性必须是对象本身的一个成员。在下例中,所有的 String 对象共享一个公用 split 方法。下面的代码将输出 false 和 true。
var s = new String("JScript");
print(s.hasOwnProperty("split"));
object.hasOwnProperty(proName)
其中参数object是必选项。一个对象的实例。
proName是必选项。一个属性名称的字符串值。
如果 object 具有指定名称的属性,那么JavaScript中hasOwnProperty函数方法返回 true;反之则返回 false。此方法无法检查该对象的原型链中是否具有该属性;该属性必须是对象本身的一个成员。在下例中,所有的 String 对象共享一个公用 split 方法。下面的代码将输出 false 和 true。
var s = new String("JScript");
print(s.hasOwnProperty("split"));
print(String.prototype.hasOwnProperty("split"));
<script type="text/javascript">
var obj = {
a: 1,
fn: function(){
},
c:{
d: 5
}
};
console.log(obj.hasOwnProperty('a'));//true
console.log(obj.hasOwnProperty('fn'));//true
console.log(obj.hasOwnProperty('c'));//true
console.log(obj.c.hasOwnProperty('d'));//true
console.log(obj.hasOwnProperty('d'));//false, obj对象没有d属性
var str = new String();
console.log(str.hasOwnProperty('substring'));//false
console.log(String.prototype.hasOwnProperty('substring'));//true
</script>