Jim
Jim

Reputation: 2322

At what point does a function object have properties?

Functions being first class objects, it seems their local data at some point must have properties, but I'm confused on when/how this happens.

Take for example:

var output = function(x){
    var s = "string";
    delete s;
    return s + " " + x;
};
console.log(output("bean"));

outputs string bean. I'm not sure if I expected it to delete s or not I was just messing around, because I thought var declared globally become a property of the window object.

I know delete doesn't work on local variables, and it only works on object properties. And because Functions are objects, I'm wondering at what point does local data in a function become a "property"

Upvotes: 3

Views: 59

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370809

I'm wondering at what point does local data in a function become a "property"

It doesn't. You're confusing a function invocation with ordinary object-like interaction with the function.

Like all objects, functions can have arbitrary key-value properties associated with them eg:

var fn = function(x){
  // do something
  // not important
};
fn.foo = 'foo';
console.log(fn.foo);

Unless you explicitly assign a property to the function like this, the function won't have properties other than the usual ones that a function has (like .prototype).

Still, assigning such arbitrary properties to a function is pretty weird, and probably shouldn't be done in most cases.

Other properties that functions often have are .name (named function name), .length (refers to the number of arguments the function takes).

This is in contrast to non-object primitives, which cannot have key-value pairs assigned to them:

'use strict';
const someStr = 'foo';
someStr.bar = 'bar';

(though, when you try to reference a property on a primitive, the interpreter will turn it into an object by wrapping it in the appropriate prototype first, so that prototypal inheritance works with it)

Upvotes: 3

Related Questions