Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - Nature of JS bound functions and function invocation operator

var obj = {};

var r1 = (obj['toString'])();
var m1 = obj['toString'];
var r2 = m1();

var r3 = (obj.toString)();
var m2 = obj.toString;
var r4 = m2();

r1 and r3 expectedly contain correct result: "[object Object]", while r2 and r4 contain "[object Undefined]" showing that m1 and m2 are not bound to object.

I can't fully comprehend how obj['toString']() is executed. I always looked this way, (obj['toString'])() -> (function obj)(). Turns out that function invocation operator looks back on what is the context. I would expect operator to not know where operands come from.

Can anyone properly explain this behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is actually a "special" behavior of the grouping operator (...):

1. Return the result of evaluating Expression. This may be of type Reference.

NOTE This algorithm does not apply GetValue to the result of evaluating Expression. The principal motivation for this is so that operators such as delete and typeof may be applied to parenthesised expressions.

So, this operator specifically does not call GetValue and thus does not return the function object itself but rather the whole reference, so that operations which expect a reference still work.


A Reference is basically an encapsulation of a value with an optional "base value" which is the object in case of a property access.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...