脚本宝典收集整理的这篇文章主要介绍了JavaScript 中this指向问题案例详解,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
无论是否在严格模式下,this 均指向 window 对象。
// 严格模式 'use strict' console.log(this === window) // true
function test() { return this === window } console.log(test()) // true
// 严格模式 'use strict' function test() { return this === undefined } console.log(test()) // true
函数作为构造函数使用时,this 指向构造出来的实例。
function Test() { this.number = 1 } let test1 = new Test() console.log(test1.number) // 1
函数为箭头函数时,this 指向函数定义时上一层作用域中的 this 值。
let test = () => { return this === window } console.log(test()) // true
let obj = { number: 1 } function foo() { return () => { return this.number } } let test = foo.call(obj) console.log(test()) // 1
函数作为对象的方法使用时,this 指向该对象。
let obj = { number: 1, getNumber() { return this.number } } console.log(obj.getNumber()) // 1
let obj = { number: 1 } function test(num) { return this.number + num } console.log(test.call(obj, 1)) // 2 console.log(test.apply(obj, [2])) // 3 let foo = test.bind(obj, 3) console.log(foo()) // 4
到此这篇关于JavaScript 中this指向问题案例详解的文章就介绍到这了,更多相关JavaScript 中this指向问题内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!
以上是脚本宝典为你收集整理的JavaScript 中this指向问题案例详解全部内容,希望文章能够帮你解决JavaScript 中this指向问题案例详解所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。