一、对象与继承
对象属性分为3种 ,数据属性 ,访问器属性 ,内置属性;
从对象中提取方法时会丢失this;可以使用bind()方法绑定;
方法中的函数会掩盖this;
A.isPrototypeOf(B)
//检查A是否为B的原型
__proto__属性可以获取和设置对象的原型,并非所有引擎都支持
设置和删除仅影响自有属性,因为原型属性是共享的。
Object.getOwnPropertyNames(obj)
//获取所有自有属性
Object.keys(obj)
//获取所有自有可枚举属性
for(key in obj)
//获取所有可枚举属性
obj.hasOwnProperty(key)
//对象是否有该自有属性
访问器继承
var proto = { get foo(){ return 'hello'} };
var obj = Object.create(proto);
obj.foo
//hello
通过 ‘=’添加属性 Writable,Enumerable ,Configurable默认为true
而通过Object.defineProperty
或Object.defineProperties
时默认值为false
Object.create(prototype)
//以prototype为原型创建对象
Object.getPrototypeOf(obj)
//获取对象原型
Object.getOwnPropertyDescriptor(obj,key)
//获取属性描述符
复制对象
function copyObject(orig){
var copy = Object.create(Object.getPrototypeOf(orig))
Ojbect.getOwnPropertyNames(orig).forEach((key)=>{
var desc = Object.getOwnPropertyDescriptor(orig ,key);
Object.defineProperty(copy ,key ,desc);
})
}
保护对象 :
防止扩展 : Object.preventExtensions(obj)
不可添加属性,但是可以修改和删除;
封闭 : Object.seal(obj)
不可添加删除属性或修改属性修饰符,但可以修改值
冻结:Obejct.freeze(obj)
不可添加修改删除,但只对浅层属性有效,例如
var a = { data : [] }
Object.freeze(a);
a.data.push(1);
a.data
//[1]
构造函数的原型自带属性constructor指向构造函数,因此它的实例可以通过这个属性访问上一级的构造函数
手动实现new 操作符
function newOperator(Constr ,args){
var thisValue = Object.create(Constr.prototype);
var result = Constr.apply(thisValue ,args);
if(typeof result==='object' && result !== null){
return result
}
return thisValue
}
术语 :两类原型 构造函数原型和实例原型;
instanceof 对于基本类型的值总是false;
123 instanceof Number //false
缺陷:
A instanceof B//类似于
Object.getPrototypeOf(A) === B.prototype
因此有
Object.create(null) instanceof Object //false
Object.prototype instanceof Object //false
// Object.prototype为原型链的末端
instanceof 跨域失效