阶段2: 探究对象中this的指向
如: {name:this.name}, 依旧通过一系列的试验来推测结论
关于普通对象
试验一:
场景: 控制台下
var lay = {
target:this
}
lay.target // 输出: window...
那是否跟层数有关系?
试验二:
var lay = {
lay1:{
lay2:{
target:this
}
}
}
lay.lay1.lay2.target // 输出: windows...
我觉得很有必要在类下试验下
class Test {
constructor() {
this.lay = {
lay1: {
lay2: {
target: this
}
}
}
}
}
var result = new Test().lay.lay1.lay2.target
console.log('result',result);
//输出: result Test {lay: {…}}
console.log('resultType',Object.prototype.toString.call(result));
//输出: resultType [object Object]
到这里细心的人已经发现了, 这个指向特质和箭头函数一样, 那么, 影响因素为"函数级元素", 不受对象级元素影响, 那么, 按照箭头函数的方式(与外侧最近一层函数或者类指向相同)
试验三
class Test {
constructor() {
this.lay = {
lay1: {
lay2: function(){
let target = {
_this:this
};
console.log("this",target._this);
console.log("thisType",Object.prototype.toString.call(target._this));
}
}
}
}
}
var result = new Test().lay.lay1.lay2()
/* 输出:
this {lay2: ƒ}
VM2232:11 thisType [object Object]
*/
很明显, 指向跟箭头函数完全一样, 并且结合之前的阶段1的结论, 可以推出输出结果,
即: 箭头函数的指向和外层包裹的函数级元素指向相同, 而外层元素指向为包裹最近的一层对象,即lay1
那么, 箭头函数和对象的this指向是什么关系, 出现上是什么关系? 就需要更深层次的探索了, 目前的思维模式不适合了已经, 需要从底层远离角度思考了, 探究到这里暂时已经够了,
关于对象解构
试验1
let conA = {
doSth(){
console.log(this)
}
}
conA.doSth() // 输出 {doSth: ƒ}
const {doSth} = {...conA}
doSth() // 输出 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
不用继续再试验了,很明显解构是在新的上下文环境中重新定义一个内存字典结构, 环境需要按照新的上下文环境计算, 可以理解成"脱离上下文流"
结论
对象中this的指向和箭头函数相同, 只受到函数级元素和class元素影响(class也是fucntion的语法糖) ,
实战时候再非很复杂的情况下一般就观察是哪个实例在使用此对象, 此对象中的this的直接指向即为那个实例
如果元素通过解构的方式拿出, 等于是重新定义, 跟原有上下文环境无关, this指向新的上下文环境
阶段3将开始逐步深入到内存和底层