Kevin Reid's blog

A note on JavaScript method call semantics

 

new
Name
Kevin Reid
Website
My Website

A note on JavaScript method call semantics

Previous Entry Add to Memories Share Next Entry
new

So. In JavaScript, an “object” is a set of “properties”: associations from strings to values. A method is just a property whose value is a function. Functions are called like “foo()”, properties are accessed like “bar.foo”, and methods are called like “bar.foo()”. Looks straightforward enough, right?

Now, how does a method access the state of its object? Without inheritance, you could just have the method functions of a given object all close over some variables; but JavaScript does have prototype inheritance, so the necessary access is provided by binding the variable “this”, in the method body, to the object the method was invoked on.

And when does this happen? When you use the method call syntax. bar.foo() is not the same as

var m = bar.foo;
m();

(It is the same as m.call(bar)call is a method on function objects which invokes them with this bound — but that's beside the point.)

So, the syntax is non-compositional.

Not only that, but it is enthusiastically so: bar.foo() is the same as (bar.foo)() — the parentheses do not break up the method call construct!

Powered by LiveJournal.com