为什么赋值运算符返回值而不是引用? [英] Why does the assignment operator return a value and not a reference?
问题描述
我在下面的网站上看到了以下示例,并认为这两个答案都是是20而不是返回的10。他写道,逗号和赋值都返回一个值,而不是引用。我不太明白这意味着什么。
I saw the example below explained on this site and thought both answers would be 20 and not the 10 that is returned. He wrote that both the comma and assignment returns a value, not a reference. I don't quite understand what that means.
我理解它与将变量传递给函数或方法有关,即原始类型是通过值传递的,而对象是通过引用传递的,但我不确定它是如何应用的case。
I understand it in relation to passing variables into functions or methods i.e primitive types are passed in by value and objects by reference but I'm not sure how it applies in this case.
我也理解上下文和'this'的值(在stackoverflow的帮助之后)但我认为在这两种情况下我仍然会调用它作为方法,foo.bar()这意味着foo是上下文,但它似乎都导致函数调用bar()。
I also understand about context and the value of 'this' (after help from stackoverflow) but I thought in both cases I would still be invoking it as a method, foo.bar() which would mean foo is the context but it seems both result in a function call bar().
为什么这是什么意思?这是什么意思?
Why is that and what does it all mean?
var x = 10;
var foo = {
x: 20,
bar: function () {return this.x;}
};
(foo.bar = foo.bar)();//returns 10
(foo.bar, foo.bar)();//returns 10
推荐答案
它与值与引用无关,它必须做使用此
值(如您所怀疑)。在JavaScript中,这个
完全按 设置函数的方式,而不是它定义的位置。您可以通过以下三种方式之一设置此
值:
It doesn't have to do with values vs. references, it has to do with this
values (as you suspected). In JavaScript, this
is set entirely by how a function is called, not where it's defined. You set the this
value in one of three ways:
- 通过以下方式调用函数使用属性访问符号的对象属性,带点分表示法(
obj.foo()
)或括号表示法(obj [foo]()
)。 - 使用
和
语句通过对象属性调用函数(实际上只是#的变体) 1,但值得分开呼叫,特别是因为源代码不明显) - 使用
apply
或调用
函数实例的功能。
- Call the function via an object property using property accessor notation, either dotted notation (
obj.foo()
) or bracketed notation (obj["foo"]()
). - Call the function via an object property using a
with
statement (really just a variant of #1, but worth calling out separately, particularly as it's not obvious from the source code) - Use the
apply
orcall
features of the function instance.
在上面的例子中,你没有做任何事情那些,所以你最终调用函数的默认这个
值,全局对象,所以 x
来了从那里而不是从你的 foo
对象。这是另一种思考代码正在做什么的方法:
In your examples above, you're not doing any of those, so you end up calling the function with the default this
value, the global object, and so x
comes from there rather than from your foo
object. Here's another way to think about what that code is doing:
var f = foo.bar; // Not calling it, getting a reference to it
f(); // Calls the function with `this` referencing the global object
如果不直接使用要实际进行调用的属性(而不是检索属性的值,然后使用该属性进行调用),此
处理不会启动in。
If you don't directly use a property to actually make the call (instead retrieving the value of the property and then making the call with that), the this
handling doesn't kick in.
这篇关于为什么赋值运算符返回值而不是引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!