this定义位置
JavaScript函数中的this不是在函数声明的时候定义的,而是在函数调用(即运行)的时候定义的
原型链
简单的回顾一下构造函数、原型和实例的关系:每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。那么假如我们让原型对象等于另一个类型的实例,结果会怎样?显然,此时的原型对象将包含一个指向另一个原型的指针,相应地,另一个原型中也包含着一个指向另一个构造函数的指针。假如另一个原型又是另一个类型的实例,那么上述关系依然成立。如此层层递进,就构成了实例与原型的链条。这就是所谓的原型链的基本概念。
new 作用
function Foo(name) {
this.name = name
return this
}
function InjectNew() {
var obj = {}
obj.__proto__ = Foo.prototype
return Foo.call(obj, name)
}
截屏2021-01-18 下午8.44.31.png
截屏2021-01-18 下午8.44.44.png
手动实现call、bind、apply
call
Function.prototype.myCall = function(thisArgs, ...args){
if(thisArgs === null || thisArgs === undefined){
thisArgs = window
}else{
thisArgs = Object(thisArgs)
}
const specialMethod = Symbol("anything");
thisArgs[specialMethod] = this
var result = thisArgs[specialMethod](args)
delete thisArgs[specialMethod]
return result
}
apply
Function.prototype.myApply = function(thisArg) {
if(thisArg === null || thisArg === undefined){
thisArg = window
}else{
thisArg = Object(thisArg)
}
const key = Symbol()
thisArg[key] = this
let args = arguments[1]
let result
if(args){
if(Array.isArray(args)) {
args = Array.from(args)
result = thisArg[key](...args)
}
} else{
result =thisArg[key]()
}
return result
}