<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>this指向</title></head><body><script>// 1function foo() {console.log(this.a)}var a = 1foo() // 1const obj = {a: 2,foo: foo}obj.foo() //2const c = new foo() // undefined//2 箭头函数function nice() {return () => {return () => {console.log(this)}}}console.log(nice()()()) // window 对象// bindlet a3 = {}let fn = function () {console.log(this)}fn.bind().bind(a3)() // => ? windowconsole.log(null == undefined);// 3var Boy = {a: 2 ,boo: function() {console.log(this.a);}}function get() {let a = 4setTimeout(()=>{let _this = Boy.boo //function(){console.log(this.a)}_this() //执行了 ,this 取决于 包裹它的作用域的this , 也就是函数 get() 的this,也就是全局对象})}get()</script>第一题:<ul><li>对于直接调用 <code>foo</code> 来说,不管 <code>foo</code> 函数被放在了什么地方,<code>this</code> 一定是 <code>window</code></li><li>对于 <code>obj.foo()</code> 来说,我们只需要记住,谁调用了函数,谁就是 <code>this</code>,所以在这个场景下 <code>foo</code> 函数中的 <code>this</code>就是 <code>obj</code> 对象</li><li>对于 <code>new</code> 的方式来说,<code>this</code> 被永远绑定在了 <code>c</code> 上面,不会被任何方式改变 <code>this</code></li></ul>第二题:<ul>首先箭头函数其实是没有 this 的,箭头函数中的 this 只取决包裹箭头函数的第一个普通函数的 this。在这个例子中,因为包裹箭头函数的第一个普通函数是 a,所以此时的 this 是 window。另外对箭头函数使用 bind 这类函数是无效的。</ul><div><img src="https://user-gold-cdn.xitu.io/2018/11/15/16717eaf3383aae8?imageslim" alt=""></div><h1> React中的this指向</h1><!-- <script>// 'use strict';function display() {console.log(this); // 'this' 将指向全局变量 、严格模式下为"undefined"}display()let obj = {tmp: 'Yes!',testLog: function () {console.log(this.tmp);}};// obj.testLog();let tmpLog = obj.testLogtmpLog()/* 在上面的例子里,当我们调用 tmpLog() 时,我们没有指定一个具体的上下文对象。这是一个没有所有者对象的纯函数调用。在这种情况下,tmpLog() 内部的 this 值回退到默认绑定。现在这个 this 指向全局对象,在严格模式下,它指向 undefined。 */class Foo {constructor(name) {this.name = name}display() {console.log(this.name);}}var foo = new Foo('Saurabh');foo.display(); // Saurabh//下面的赋值操作模拟了上下文的丢失。//与实际在 React Component 中将处理程序作为 callback 参数传递相似。var display = foo.display;display(); // TypeError: this is undefined</script>--><script>for (var i = 1; i < 5; i++) {setTimeout(function timer() {console.log(i)}, i * 1000)}</script><script>var obj = {id: 'awesome',cool: function cooFn() {console.log(this.id)}}var id = 'not awesome'obj.cool() // awesonmesetTimeout(obj.cool, 100) // not awesome</script></body></html>
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。