我当时正在研究这个内部对象方法的行为,我被困在了一个输出上。
这是密码。
'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.
this总是引用其封闭的父函数。词法范围发布于 2020-03-22 13:41:53
在案例2中,括号不会改变()左侧的函数引用值来自对象属性引用的事实。因此,函数调用的方式与案例1完全相同,对象引用绑定到this。
然而,在案例4中,这些圆括号中的||值会导致这种关系丢失;剩下的就是没有任何相关对象的函数引用。这是因为||的逻辑并不关心函数引用来自对象属性查找的事实,因此它的结果值只是函数引用“裸”。
至于你接下来的问题,这两种说法的措辞都不正确.this的值确实取决于如何调用函数,但这与函数的来源或声明方式无关。在箭头函数中,this的值不是其词法父函数的引用,它与词法父函数中的this值相同。
发布于 2020-03-22 14:51:06
@Pointy已经回答了你的问题。只是为了好玩:了解您现在知道的内容,您可以让您的obj.go方法在它自己的范围内运行,并封装在一个箭头函数表达式中:
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)([...])`);.as-console-wrapper { top: 0; max-height: 100% !important; }
发布于 2020-03-22 13:44:46
实际上,#s 3和4返回[object Window]
见评论:
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
https://stackoverflow.com/questions/60800013
复制相似问题