跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

js中hasOwnProperty的属性及实例用法详解

1、js不会保护hasOwnProperty被非法占用,如果一个对象碰巧存在这个属性, 就需要使用外部的hasOwnProperty 函数来获取正确的结果。

2、当检查对象上某个属性是否存在时,hasOwnProperty 是唯一可用的方法。

实例var foo = {hasOwnProperty: function() {return false;},bar: 'Here be dragons'};foo.hasOwnProperty('bar'); // 总是返回 false// 使用其它对象的 hasOwnProperty,并将其上下文设置为foo ({}).hasOwnProperty.call(foo, 'bar'); // true

知识点扩展:

判断自身属性是否存在

var o = new Object();o.prop = 'exists';

function changeO() {o.newprop = o.prop;delete o.prop;}

o.hasOwnProperty('prop'); // true changeO();o.hasOwnProperty('prop'); // false

判断自身属性与继承属性

function foo() {this.name = 'foo'this.sayHi = function () {console.log('Say Hi')}}

foo.prototype.sayGoodBy = function () {console.log('Say Good By')}

let myPro = new foo()

console.log(myPro.name) // foo console.log(myPro.hasOwnProperty('name')) // true console.log(myPro.hasOwnProperty('toString')) // false console.log(myPro.hasOwnProperty('hasOwnProperty')) // fasle console.log(myPro.hasOwnProperty('sayHi')) // true console.log(myPro.hasOwnProperty('sayGoodBy')) // false console.log('sayGoodBy' in myPro) // true

遍历一个对象的所有自身属性

在看开源项目的过程中,经常会看到类似如下的源码。for...in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。

var buz = {fog: 'stack'};

for (var name in buz) {if (buz.hasOwnProperty(name)) {alert("this is fog (" + name + ") for sure. Value: " + buz[name]);}else {alert(name); // toString or something else}}注意 hasOwnProperty 作为属性名

JavaScript 并没有保护 hasOwnProperty 属性名,因此,可能存在于一个包含此属性名的对象,有必要使用一个可扩展的hasOwnProperty方法来获取正确的结果:var foo = {hasOwnProperty: function() {return false;},bar: 'Here be dragons'};

foo.hasOwnProperty('bar'); // 始终返回 false

// 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法// 使用另一个对象的`hasOwnProperty` 并且call ({}).hasOwnProperty.call(foo, 'bar'); // true

// 也可以使用 Object 原型上的 hasOwnProperty 属性Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

到此这篇关于js中hasOwnProperty的属性及实例用法详解的文章就介绍到这了,更多相关js中hasOwnProperty的属性用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:JS中hasOwnProperty方法用法简介js中hasOwnProperty()方法详解JavaScript中in和hasOwnProperty区别详解JS中的hasOwnProperty()和isPrototypeOf()属性实例详解javascript中hasOwnProperty() 方法使用指南js中的hasOwnProperty和isPrototypeOf方法使用实例JavaScript isPrototypeOf和hasOwnProperty使用区别使用hasOwnProperty时报错的解决方法

相关文章