关于js中属性那些事

1         //为object对象扩展create函数,指定继承对象
2         if (typeof Object.create !== 'function') {
3             Object.create = function (o) {
4                 var F = function () { };
5                 F.prototype = o;
6                 return new F();
7             }
8         }
 1         let oa = {
 2             name: 'zhangw'
 3         };
 4 
 5         //es5中为对象定义属性,可设定属性参数,如:不可枚举、不可修改等
 6         Object.defineProperty(oa, 'interest', {
 7             value:'table tennis',
 8             configurable: false,
 9             writable: false,
10             enumerable: false
11         });
12 
13         for (let i in oa) {
14             //因为增加的属性被设置为不可枚举,此处不会打印出来interest
15             if (oa.hasOwnProperty(i)) {
16                 console.log(i, oa[i]);
17             }
18         }

hasOwnProperty可能是某对象的自定义属性,为了安全的使用它,最好的方法是直接从Object的原型对象上拿来调用:

 1         var foo = {
 2             hasOwnProperty: function () {
 3                 return false;
 4             },
 5             bar: 'very good.'
 6         };
 7         foo.hasOwnProperty('bar'); // 始终返回 false
 8 
 9         // 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法
10         // 使用另一个对象的`hasOwnProperty` 并且call
11         ({}).hasOwnProperty.call(foo, 'bar'); // true
12 
13         // 也可以使用 Object 原型上的 hasOwnProperty 属性
14         Object.prototype.hasOwnProperty.call(foo, 'bar'); // true

猜你喜欢

转载自www.cnblogs.com/glzgc/p/9590710.html