tip
首先,我知道这篇文章很无聊,无非就是关于 js 中的 this,并且也已经有千千万万的文章写过这部分内容了;
但是,我还是想写一篇关于 js 中的 this 的文章,算是一个总结归纳吧;(大神们可以绕行看我的其他文章)
在 js 中,this 这个上下文总是变化莫测,很多时候出现 bug 总是一头雾水,其实,只要分清楚不同的情况下如何执行就 ok 了。
全局执行
首先,我们在全局环境中看看它的 this 是什么:
first. 浏览器:
console.log(this);// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
可以看到打印出了 window 对象;
second. node:
console.log(this);// global
可以看到打印出了 global 对象;
总结:在全局作用域中它的 this 执行当前的全局对象(浏览器端是 Window,node 中是 global)。
函数中执行
纯粹的函数调用
这是最普通的函数使用方法了:
function test() { console.log(this);};test();// Window {speechSynthesis: SpeechSynthesis, caches: CacheStorage, localStorage: Storage, sessionStorage: Storage, webkitStorageInfo: DeprecatedStorageInfo…}
我们可以看到,一个函数被直接调用的时候,属于全局调用,这时候它的 this 指向 全局对象;
严格模式 ‘use strict';
如果在严格模式的情况下执行纯粹的函数调用,那么这里的的 this 并不会指向全局,而是 undefined,这样的做法是为了消除 js 中一些不严谨的行为:
'use strict';function test() { console.log(this);};test();// undefined
当然,把它放在一个立即执行函数中会更好,避免了污染全局:
(function (){ "use strict"; console.log(this);})();// undefined
作为对象的方法调用
当一个函数被当作一个对象的方法调用的时候:
var obj = { name: 'qiutc', foo: function() { console.log(this.name); }}obj.foo();// 'qiutc'
这时候,this 指向当前的这个对象;
当然,我们还可以这么做:
function test() { console.log(this.name);}var obj = { name: 'qiutc', foo: test}obj.foo();// 'qiutc'
同样不变,因为在 js 中一切都是对象,函数也是一个对象,对于 test ,它只是一个函数名,函数的引用,它指向这个函数,当 foo = test,foo 同样也指向了这个函数。
如果把对象的方法赋值给一个变量,然后直接调用这个变量呢:
新闻热点
疑难解答
图片精选