1.in和hasOwnProperty的区别
in操作符检查属性是否在对象及其原型链中;
hasOwnProperty只会检查属性是否在该对象中,所有普通对象都可以通过Object.prototype的委托来访问hasOwnProperty
通过Object.create(null)创建的,可通过Object.prototype.hasOwnProperty.call(obj,“a”),显式的绑定到obj上。
2. enumerable属性
var myObject = { };
Object.defineProperty(
myObject,
"a"
,
// 让a像普通属性一样可以枚举
{ enumerable: true, value: 2 }
);
Object.defineProperty(
myObject,
"b"
,
// 让b不可枚举
{ enumerable: false, value: 3 }
);
myObject.b; // 3
("b" in myObject); // true
myObject.hasOwnProperty( "b" ); // true
// .......
for (var k in myObject) {
console.log( k, myObject[k] );
}
// "a" 2 ,b并不会出现在for...in循环中。
myObject.propertyIsEnumerable("a")可以用来检测是否可枚举,检测给定的属性名是否直接存在于对象中。
3.Object.keys(…)和Object.getOwnPropertyNames(…)区别
Object.getOwnPropertyNames(…)返回一个数组,包含所有属性,无论他们是否可枚举,而Object.keys(…)返回的是包含所有可枚举属性的数组。
bject.preventExtensions(…),Object.seal(…),Object.freeze(…)来设置对象(及其属性)的不可变性级别。
自定义遍历器
Object.defineProperty( myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function() {
var o = this;
var idx = 0;
var ks = Object.keys( o );
return {
next: function() {
return {
value: o[ks[idx++]],
done: (idx > ks.length)
};
}
};
}
} );
// 手动遍历myObject
var it = myObject[Symbol.iterator]();
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // { value:undefined, done:true }
// 用for..of遍历myObject
for (var v of myObject) {
console.log( v );
}
// 2
// 3
原型继承
function Foo(name) {
this.name = name;
}
Foo.prototype.myName = function() {
return this.name;
};
function Bar(name,label) {
Foo.call( this, name );
this.label = label;
}
// 我们创ٛ建了一个新的Bar.prototype对像并关联到Foo.prototype
Bar.prototype = Object.create( Foo.prototype );
// 现在没有Bar.prototype.constructor
// 需要手动的修复
Bar.prototype.myLabel = function() {
return this.label;
};
var a = new Bar( "a"
,
"obj a" );
a.myName(); // "a"
a.myLabel(); // "obj a"
把新的对象关联到我们希望的对象上
比较好的关联方法
检查“类”关系
弊端:只能处理对象和函数之间的关系,无法判断是否通过prototype链关联。
//用来判断o1是否关联到o2的辅助函数
function isRelatedTo(o1, o2) {
function F(){}
F.prototype = o2;
return o1 instanceof F;
}
var a = {};
var b = Object.create( a );
isRelatedTo( b, a ); // true
//显然,o1实际上并没有继承F也不是有F构造的,所以使用instanceof并不能用来判断。
检查是否关联的3种方法
1.//b是否出现在c的prototype链中
b.isPrototypeOf( c )
2.//获取一个对象的prototype链
Object.getPrototypeOf(a)
3.proto