this的指向问题
原先总结过this指向问题(js 中 this 的指向性问题),但看了大佬们写的之后,觉得自己写的还不是很通俗易懂,所以,结合大佬们的,重学重写一遍。
this
并不是 JavaScript 特有的特性,在 c++、java 等面向对象的语言中也存在这个关键字。他们中的this
很好理解,指向的是当前类的实例对象。那在 JavaScript 中呢,我们先看两个例子:
function Person(name){ this.name = name } // 1. 当作构造函数调用 let p = new Person('程序员') // 输出:程序员 // 可以看到实例可以访问到绑定在 this 上的属性,this 指向 p 实例 // 因为 new 操作符可以改变 this 指向,详情可以看之前的文章:深入理解 Object console.log(p.name) // 2. 普通函数调用 function Man(name){ this.name = name } Man('程序猿') console.log(window.name) // 程序猿,this 指向了 window 对象,Man 函数没有所属对象
从例子可以看出,随着函数执行,就会产生一个this
值,这个this
值存储着调用该函数的对象的值。因此可以推断,this
指向的永远是函数的调用者。
举几个this
指向的场景:
1.函数没有所属对象而直接调用时,this
指向的是全局对象
var val = 1 var obj = { val: 2, method: function() { let foo = function() { console.log(this.val) } foo() // foo 函数的执行没有绑定对象,所以 this 指向 window } } obj.method() // 1
2.this
指向所属对象
var val = 1 var obj = { val: 2, method: function() { console.log(this.val) } } obj.method() // 2,this 指向函数所属对象 obj
3.this
指向call()
、apply()
、bind()
函数调用后重新绑定的对象
var val = 1 var obj = { val: 2 } var method = function() { console.log(this.val) } method() // 1 方法没有绑定对象,执行 window method.call(obj) // 2 ,call 将函数调用的主体改为到 obj method.apply(obj) // 2 ,apply 将函数指向的主体改为 obj var newM = method.bind(obj) // bind 将函数指向的主体改为 obj newM() // 2
再看个经典的例子:
function f(k) { this.m = k return this } var m = f(1) var n = f(2) console.log(m.m) // 2.m undefind console.log(n.m) // 2 window.n.m = window.m = 2
f()
函数的调用没有所属对象,所以this
指向window
。
当执行f(1)
,this.m = window.m = 1
,返回this
,即返回window
,所以此时window.m = window
。
当执行 f(2),this
同样指向window
,this.m = window.m = 2
,通过return
语句将window
赋值给n
,此时window.n = window
。
所以m.m = 2.m
,输出undefined
;n.m = (window.n).m = window.m = 2
。
至此我们大体学习了this
的相关指向知识。
里面关于new
操作符改变this
指向的问题,可以查看文章:
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » this的指向问题
码云笔记 » this的指向问题