大概会用一个系列,讲一下面试过程当中常常会问的一些问题,以及我以为应该能够怎么回答。面试
固然,个人回答也并非标准答案,只是我本身的一些理解,也欢迎其余人发表本身的想法。函数
做为本系列的第一篇文章,就先讲讲被问的最多的 js 继承
问题,可是应该不会写原型链相关的东西,测试
先列举一个最简单的问题:es5
写一个inherit(superClass, subClass)
方法,实现subClass
继承superClass
继承有哪些特征,如何检测一个继承是否成功?
foo instanceof superClass
测试function inherit(p, s) { s.prototype = Object.create(p.prototype, { constructor: { value: s, enumerable: false, writebale: true, configurable: true } }) Object.setPrototypeOf ? Object.setPrototypeOf(s, p) : s.__proto__ = p }
function inherit(p, s) { var f = new Function () f.prototype = new p() var r = new f() s.prototype = r s.prototype.constructor = s s.__proto__ = p f = null r = null }
Object.create
是什么?怎么使用?Object.create(proto, [propertiesObject])
Object.create
提供了一个建立对象的方法,使用现有的对象做为新建立对象的__proto__
,同时能够传入添加到新对象的可枚举属性, 这些属性能够对应到Object.defineProperties
的第二个参数中。prototype
返回值为所建立的新对象.code
例如:对象
s.prototype = Object.create(f.prototype, { constructor: { value: s, enumberable: false, writealble: true, configurale: true } })
Object.defineProperties
是什么?怎么使用?能够列举一个 Object.definProperties
的实际应用吗?Object.defineProperties
能够直接在一个对象上定义或修改属性,并返回该对象。继承
例如:ip
target = Object.defineProperties(target, props)
本质上 Object.defineProperties
是对Object.defineProperty
的集中调用,能够理解为是Object.definePeropety
的复数版。原型链
Object.defineProperty
的使用方法为:
target = Object.defineProperty(target, prop, descriptor)
因此本质上Object.defineProperties
就是以下代码:
Object.keys(props).forEach(function (prop) { let descriptor = props[prop] Object.defineProperty(target, prop, descriptor) })
其中 descriptor
的可选值有如下集中:
true
时,该属性描述符才可以被改变,同时该属性也能从对应的对象上被删除。默认为 false
。true
时,该属性才可以出如今对象的枚举属性中。默认为 false
。undefined
undefined
。undefined
。若是一个 descriptor 不具备 value
, writebale
, get
和 set
任意一个关键字,那么将会被认为是一个数据描述符。
若是一个描述符同时具备(value
或writbale
)和(get
或set
),将会产生一个异常.
继承多个父类的话,可使用 Object.assign
方法。
例如:
targe = Object.assign({}, superClassA, superClassB, ...)
可是继承多个父类的话,子类就不能经过 son instanceof superClass
这样的验证了.
Object.assign
是什么?怎么用?用的时候有哪些须要注意?Object.assign
方法用于将全部可枚举属性从一个或多个源对象复制到目标对象,并返回目标对象,例如:
target = Object.assign(target, source)
若是具备同名属性,那么在后面对象中的属性,将会覆盖目标对象中的属性。
须要注意如下几点:
null
, undefined
会被忽略,而且只有字符串的包装对象才可能有自身可枚举的属性.symbol
类型的属性Object.assign
会调用 setter
和 getter
吗?调用的是哪里的setter
和getter
?Object.assign
会调用源对象的 getter
,并把源对象的 getter
的返回值当作新对象的该属性的值。setter
则是会直接加在新建立的对象中,而不会沿用源对象的 setter
.
Object.getOwnPropertyDescriptor
是什么?主要用来作什么?Object.getOwnPropertyDescriptor
返回直到对象上一个自有属性对应的描述符,例如:
Object.getOwnPropertyDescriptor(obj, prop)