首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么在方法[javascript]中,“this”结果为“未定义”

为什么在方法[javascript]中,“this”结果为“未定义”
EN

Stack Overflow用户
提问于 2020-03-22 13:37:22
回答 3查看 89关注 0票数 2

我当时正在研究这个内部对象方法的行为,我被困在了一个输出上。

这是密码。

代码语言:javascript
复制
'use strict';

let obj, method;

obj = {
  go() { alert(this); }
};

obj.go();               // (1) [object Object]

(obj.go)();             // (2) [object Object]     QUESTION 2

(method = obj.go)();    // (3) undefined

(obj.go || obj.stop)(); // (4) undefined     ------> Doubt  <-------------------

那么,如果第四个在逻辑上等同于第二个,为什么逻辑会导致上下文丢失?

部件-2

如果我错了,请纠正我。

函数declaration/expression.

  • Inside箭头函数调用/调用它的方式,this总是引用其封闭的父函数。词法范围
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-03-22 13:41:53

在案例2中,括号不会改变()左侧的函数引用值来自对象属性引用的事实。因此,函数调用的方式与案例1完全相同,对象引用绑定到this

然而,在案例4中,这些圆括号中的||值会导致这种关系丢失;剩下的就是没有任何相关对象的函数引用。这是因为||的逻辑并不关心函数引用来自对象属性查找的事实,因此它的结果值只是函数引用“裸”。

至于你接下来的问题,这两种说法的措辞都不正确.this的值确实取决于如何调用函数,但这与函数的来源或声明方式无关。在箭头函数中,this的值不是其词法父函数的引用,它与词法父函数中的this值相同。

票数 1
EN

Stack Overflow用户

发布于 2020-03-22 14:51:06

@Pointy已经回答了你的问题。只是为了好玩:了解您现在知道的内容,您可以让您的obj.go方法在它自己的范围内运行,并封装在一个箭头函数表达式中:

代码语言:javascript
复制
let obj, method, otherMethod, m2;

obj = {
  foo: `obj.foo here, saying: done`,
  go(txt = ``) { console.log(`obj.go here, called as: ${txt} => ${this.foo}`); }
};
(txt => obj.go(txt))(`(txt => obj.go(txt))([...])`);
(method = txt => obj.go(txt))(`(method = txt => obj.go(txt))([...])`);
(obj.go && 
  (txt => obj.go(txt)) || 
  obj.stop)(`(obj.go && txt => obj.go(txt) || obj.stop)([...])`);

// or use a wrapper (factory function)
const wrap = (...[obj, method, txtArg]) => () => obj[method](txtArg);
(otherMethod = wrap(obj, `go`, `(otherMethod = wrap(obj, \`go\`, \`[...]\`))()`))();

// or make `go` a getter and that getter a factory function
let otherObj = {
  foo: `and hithere, here's otherObj.foo`,
  get go() { return txt => 
    console.log( `otherObj.go here, called as: ${txt} => ${this.foo}` ); }
};

(m2 = otherObj.go)(`(m2 = otherObj.go)([...])`);
代码语言:javascript
复制
.as-console-wrapper { top: 0; max-height: 100% !important; }

票数 1
EN

Stack Overflow用户

发布于 2020-03-22 13:44:46

实际上,#s 3和4返回[object Window]

见评论:

代码语言:javascript
复制
let obj, method;

obj = {
  go() { alert(this); }
};

obj.go();               // [object Object] represents obj

(obj.go)();             // [object Object] represents obj

(method = obj.go)();    // [object Window] because the go method is not running in the context of obj

(obj.go || obj.stop)(); //  Same as above

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60800013

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档