《Javascript权威指南》学习笔记 第六章 对象

原创
2014/11/14 11:02
阅读数 181

6.4检测属性

in 运算符的左侧是属性名,右侧是对象。如果对象的自由属性或继承属性中包含这个属性则返回true

var o = { x: 1 }

"x" in o;  //=>true

"y" in o;  //=>false

"toString" in o;  //=>true


对象的hasOwnProperty()方法用来检测给定的名字是否是对象的自有属性。对于继承属性将返回false

var x = { y: 3 };

var o = Object.create(x);

o.x = 1;

o.hasOwnProperty('x'); //=>true

o.hasOwnProperty('y');  //=>false

o.hasOwnProperty('toString');  //=>false


propertyIsEnumerable()值检测自有属性且这个属性的可枚举性为true时它才返回true。

var o = Object.create({ x: 3 });

o.y = 5;

o.propertyIsEnumerable('x'); // false 继承来的

o.propertyIsEnumerable('y'); // true 自有属性可枚举

Object.prototype.propertyIsEnumerable('toString'); //不可枚举


除了in运算符意外,另一种简单的方法是使用“!==” 判断一个属性是否是undefined

var o = { x: 1 };

o.x !== undefined; //true o中有属性x

o.y !== undefined; //false o中没有属性y

o.toString !== undefined; //true o中有属性toString


但如果某个属性的值为undefined时,该方法不适用

var o = { x: undefined };

o.x !== undefined; //false o中有属性x 但是他的值是undefined

o.y !== undefined; //false o中没有属性y

o.toString !== undefined; //true o中有属性toString


6.5枚举属性

var o = {x:1, y:2, z:3};

o.propertyIsEnumerable('toString'); //false 不可枚举

for(p in o)

console.log(p); // 不输出 toString 因为toString不可枚举


/*

 * 把p中的可枚举属性复制到o中,并返回o

 * 如果o和p中含有同名属性,则覆盖o中的属性

 * 这个函数并不处理getter和setter以及复制属性

 */

function extend(o,p){

for(prop in p){

o[prop] = p[prop];

}

return o;

}



/*

 * 将p中的可枚举属性复制至o中,并返回o

 * 如果o和p中有同名的属性,o中的属性将不受影响

 * 这个函数并不处理getter和setter以及复制属性

 */

function merge(o,p){

for (prop in p){

if (o.isOwnProperty[prop]) continue; //过滤掉已经在o内存在的属性

o[prop] = p[prop];

}

return o;

}


/*

 * 如果o中的属性在p中没有同名属性,则从o中删除这个属性

 * 返回o

 */

function restrict(o,p){

for(prop in p){

delete o[prop]; //删除一个不存在的属性不会报错 = =

}

}


/*

 * 返回一个新对象,这个对象同时拥有o的属性和p的属性

 * 如果o和p中有重名,使用p中的属性

 */

function union(o,p){

return extend(extend({},o),p); //需要返回一个新对象,所以要传入一个空对象~

}


/*

 * 返回一个数组,这个数组包含的是o中可枚举的自有属性的名字

 */

function keys(o){

if(typeof o !== "object") throw TypeError();

var n = [];

for (prop in o){

if(o.isOwnProperty[prop]){

n.push(prop)

}

}

return n;

}

6.7 属性的特性

属性的特性 value writable enumerable configurable

通过调用 Object.getOwnPropertyDescriptor()可以或则某个对象特定属性的属性描述:

//输出Object {value: 1, writable: true, enumerable: true, configurable: true}

Object.getOwnPropertyDescriptor({x:1},'x');


对于继承属性和不存在的属性 返回 undefined

Object.getOwnPropertyDescriptor({},"x");

Object.getOwnPropertyDescriptor({},"toString");


调用Object.difineProperty()

var o = {};

Object.defineProperty(o,'x',{ value:1,

writable: true;

enumerable: false;

configurable:true;})


6.8 对象的三个属性

Object.prototype 作为它的圆形 通过new创建的对象使用构造函数的prototype属性作为它的圆形。通过Object.create()创建的对象使用第一个参数(可以是null)作为他们的原形

将对象传入Object.getPrototypeOf()可以查询它的原形

var p = {x:1}

var o = Object.create(p)

Object.getPrototypeOf{o}

p.isPrototypeOf(o) // true

Object.prototype.isPrototypeOf(o) // true


展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部