Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on Function call; `this` gets bound to unexpected value

Parent

Function call; `this` gets bound to unexpected value

+7
−0

I recently encountered a strange situation in javascript; if I have:

let obj = {
  a: function() {
    return (this === obj) ? this.b : 'bye';
  },
  b: 'hello'
};

I can call obj.a with this bound to obj by simply calling obj.a() (producing "hello").

The following allows me to call obj.a with this bound to the global object (and the result is "bye"):

let a = obj.a;
console.log(a());

I assumed that I could shorten my code to call obj.a, with this unbound from obj, using:

console.log((obj.a)())

I was surprised to find that when the above function is called, this is still bound to obj! It seems that here, (obj.a) resolves to not just the function, but also holds information about the "boundedness" of the function!

I was especially surprised since I had assumed that any code which declares let v = <some code>; and then goes on to use v was always interchangeable with using <some code> inline, so long as it is wrapped in parentheses.

  • Is this intentional functionality? (I assume so)
  • What technical vocabulary can be used to describe this situation? (E.g. "boundedness" is my own invention)
  • Where in the spec is this behaviour outlined?
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

Post
+6
−0

This MDN link might help to explain that:

When a function is called as a method of an object, its this is set to the object the method is called on.

Which is your first example (calling obj.a()). But the link above also mentions that "this behavior is not at all affected by how or where the function was defined". So I could do the opposite of what you did, and create the function outside the object and then attach it:

let obj = {
  b: 'hello'
};

function f() {
    return (this === obj) ? this.b : 'bye';
}

obj.a = f;
console.log(obj.a()); // hello
console.log(f()); // bye

That's because what really matters is how you invoke the function. If called from a member of the object, the this value is set to the object, regardless of where the function was defined. So calling it in a "non-object" context doesn't set this to the object.

BTW, calling (obj.a)() is the same as obj.a() because in this case the first pair of parenthesis is redundant ((obj.a) evaluates to the obj.a function, and obj.a === (obj.a) is true). But it's not the same as setting a variable f = obj.a and then calling f() because, as said above, how the function is called influences the value of this, and by calling f(), I'm not invoking the function as a method of an object.

To accomplish the behaviour of "preserving" this, you could use bind or call, which are two ways of controlling which value of this the function sees:

let obj = {
  a: function() { return (this === obj) ? this.b : 'bye'; },
  b: 'hello'
};
let a = obj.a;
console.log(a()); // bye

// with call, using "obj" as the "this" value
console.log(a.call(obj)); // hello

// bind, returns another function that uses "obj" as the "this" value
let boundFunc = obj.a.bind(obj);
console.log(boundFunc()); // hello

I'm not sure about the exact terminology, but this section of the spec mentions the ResolveThisBinding operation, whose definition says: "It determines the binding of the keyword this using the LexicalEnvironment of the running execution context." - and ResolveThisBinding operations calls GetThisEnvironment, whose definition says: "It finds the Environment Record that currently supplies the binding of the keyword this".

So I guess "binding" would be an appropriate term.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

General comments (1 comment)
General comments

Skipping 2 deleted comments.

Gershy‭ wrote over 4 years ago

ResolveThisBinding and GetThisEnvironment are very useful to know about!