一、JS基础-原理实现
- 实现new
function newOperator(ctor) {
if (typeof ctor !== 'function') {
throw new Error('Constructor not a function')
}
const newObj = Object.create(ctor.prototype)
const args = [].slice.call(arguments, 1)
const returnObj = ctor.apply(newObj, args)
const isObj = typeof returnObj==='object' && returnObj !== null;
const isFunction = typeof returnObj === 'function'
if (isObj || isFunction) {
return returnObj
}
return newObj
}
- 实现bind
基本结论:
- bind是函数原型对象上,每个函数都可以调用
- 函数使用bind后,被调用对象是传入bind的第一个参数
- 当new 被bind后的函数时,this指向了新生成的对象
Function.prototype.bindMock = function(target) {
const originalFun = this;
const args = [].slice.call(arguments,1)
return function bound() {
const boundArgs = [].slice.call(arguments)
const finalArgs = args.concat(boundArgs)
if(this instanceof bound