this指向

/** 一、全局环境下*/

// console.log(this == window)

// 严格模式下普通function的this为undefined

// 非严格模式下, this默认指向全局对象window

// function f2(){

//     return this

// }

// console.log(f2()===window)

/** 二、对象中的this

 * 对象内部方法的this指向调用这些方法的对象

 * 1.函数的定义位置不影响其this指向,this指向只和调用函数的对象有关

 * 2.多层嵌套的对象,内部方法的this指向离被调用函数最近的对象(window也是对象,其内部对象调用方法的this指向内部对象,而非window)*/

// var obj = {

//     prop: 34,

//     show: function () {

//         console.log(this)

//         console.log(this.prop)

//         return this

//     }

// }

// const objRes = obj.show()

// console.log(objRes === obj)

// // 从上面调用的例子来看, obj 调用了 show方法,故 show方法内部的this指向obj,即对象内部的普通function 谁调用,this就指向谁(window可视为一个大对象,故也是如此)

/** 三、原型链中this

 *  原型链中方法的this仍然指向调用它的对象,与二 一致

*/

// var obj = {

//     show: function(){

//         console.log(this)

//         console.log(this.a + this.b)

//     }

// }

// var newObj = Object.create(obj)

// newObj.a = 2

// newObj.b = 4

// console.log(newObj.show())

// //{ a: 2, b: 4 }

// //6

// // 输出结果如上,因为Object.create()是以目标对象作为新创建的对象的__proto__

/** 四、setTimeout & setInterval

 *  对于延时函数内部的回调函数的this指向全局对象window(只对于普通函数,箭头函数除外,也可以通过bind改变其内部函数的this指向)

 */

// function Person (){

//     this.age = 18

//     setTimeout(function(){

//         console.log(this)

//         console.log(this.age)

//     }, 3000)

// }

// function Person (){

//     this.age = 18

//     setTimeout((function(){

//         console.log(this)

//         console.log(this.age)

//     }).bind(this), 3000)

// }

// var p = new Person()

/** 五、箭头函数的this

 *  箭头函数不绑定this, 它会捕捉其所在(即定义的位置)上下文的this值,作为自己的this值

 *  1. 所以call()/apply()/bind() 方法对于箭头函数来说只是传入参数,对它的this毫无影响

 *  2. 考虑到this是词法层面上的,严格模式与this相关的规则都降被忽略

*/

// function Person (){

//     const that = this

//     this.age = 18

//     setTimeout(()=>{

//         console.log(this)

//         console.log(this.age)

//         console.log(that === this)

//         function showAge(){

//             console.log("========", this)

//             console.log("========", this.age, that.age)

//         }

//         showAge()

//     }, 3000)

// }

// var p = new Person()

/** 六、在函数没有任何对象调用时,this默认指向window(非严格模式下,严格模式下为undefined)

 *  例子如上面, showAge() this指向window

*/

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容