_ proto _ 原理
Object.defineProperty(Object.prototype, '__proto__', {
get() {
return Object.getPrototypeOf(this)
},
set(o) {
Object.setPrototypeOf(this, o)
return o
}
})
bind()原理
Function.prototype.bind = function() {
let self = this
let context = [].shift.apply(arguments)
let ortherArgs = [].slice.apply(arguments)
return function(...args) {
return self.apply(context, [...ortherArgs, ...args])
}
}
let obj = {
a: 'a'
}
function fun(a, b) {
console.log(this.a, a, b)
}
let example = fun.bind(obj, 'a')
example('b')
模拟new实现
function mockNew() {
let Constructor = [].shift.call(arguments)
let obj = {}
obj.__proto__ = Constructor.prototype
let r = Constructor.apply(obj, arguments)
return r instanceof Object ? r : obj
}
let animal = mockNew(Animal, '哺乳类')
console.log(animal)
instaceof 判断原始类型
class PrimitiveString {
static [Symbol.hasInstance](x) {
return typeof x === 'string'
}
}
console.log('hello world' instanceof PrimitiveString)