Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function not serializable?

Background

In the Meteor docs for Meteor.call(), it reads:

If you include a callback function as the last argument (which can't be an argument to the method, since functions aren't serializable)...

I have ran something similar to Meteor.call('name', function() {console.log('abc');}, function() {}) before, where function() {console.log('abc');} is passed in as an argument, and the empty function() {} is used as a stub for the asynchronous callback. And it works.

So is that statement telling me I shouldn't pass any functions as arguments to functions, or only applies for callback functions.

Question

In either case, why is that function not serializable? My shallow understanding is only that a serializable object is one where you can turn it into a sequence of bits (1's and 0's), and since everything digital are sequence of bits, I don't understand why functions are not serializable.

I found some explanations, but they are all related to Java, and for someone who doesn't already know the significance of serialization, it's not much help.

Why is a function not serializable? (and how does it relate to Meteor.call()?)

like image 738
dayuloli Avatar asked May 08 '26 13:05

dayuloli


1 Answers

In most cases, serializable means that you can convert something into a language-agnostic representation and reconstruct the original state somewhere else. E.g. the array [0,1,2] could be serialized to JSON "[0,1,2]" and deserialized somewhere else.

In either case, why is that function not serializable?

A function object (in JS) consist of two parts: its body (code) and the environment it is defined in. Every function is a closure. Getting the source of the function is easy, but you can't get the state of its environment.

Example:

var foo = 42;
function bar() {
    console.log(foo);
}

thirdService(bar);

thirdService has no idea about the environment the function is defined in. All it can do is get a string representation of the body of the function, but it doesn't know the value of foo.

like image 88
Felix Kling Avatar answered May 11 '26 03:05

Felix Kling