0

If functions are objects in javascript, then why can't they have name-value pair syntax for their properties? For example, why is the following not possible/allowed?

function xx() {
    name: 'jhg'
}
alert(xx.name);

and vice versa:

var person = {
    this.age = 32;
};
alert(person.age);
chazsolo
  • 7,873
  • 1
  • 20
  • 44
user8783104
  • 185
  • 2
  • 11
  • 1
    Possible duplicate of [javascript : function and object...?](https://stackoverflow.com/questions/5958417/javascript-function-and-object) – 1stthomas Nov 14 '17 at 17:13

3 Answers3

3

You could assign the properties, you want, but not Function.name, which is a read only property with the name of the function.

function xx() { }

xx.name = 'jhg'; // is read only, because it's the function's name
xx.foo = 'bar';

console.log(xx.name);
console.log(xx.foo);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Because function declarations aren't object initializers. They're just different syntaxes, for different purposes, with different use cases and design criteria. Arrays are also objects, but we use a different initializer notation for them, too. Same with regular expressions.

(Note that your first example is perfectly valid and will run; name is a label, not a property name, and labels an ExpressionStatement that isn't used for anything.)

(Also note that functions do, as of ES2015, have a built-in name property. That's just not how you initialize it. [That function's name will be "xx" in your example.])

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

They are objects, but they are not object literals.

A function can be used to create an instance of an object. For example:

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log('Hi, my name is ' + this.name);
    };
}

var bob = new Person('Bob', 24);

The bob variable is an instance of the Person function. You can access the properties from bob like this:

console.log( bob.name ) // "Bob"

You could also define it literally, like this:

var bob = {
    name: 'Bob',
    age: 24
};

The function syntax is used to create functions. They are templates that can be used over and over again. The object literal syntax is used when you only want one instance, or also for data, without any behavior attached to it.

wes24
  • 43
  • 6