3

I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}

does test1 is a part of stringFunction or just a naming convention.Thanks in advance

Sri kanth
  • 55
  • 1
  • 7
  • Neither, it's a property definition. Functions in JS are objects. – Teemu Jul 05 '17 at 05:51
  • but on doing a typeof for stringFunction it returns as a function not an object – Sri kanth Jul 05 '17 at 05:55
  • @Srikanth: yes... they're "weird". But if weirdness and special cases scare you then probably Javascript is not your language :-D – 6502 Jul 05 '17 at 05:58
  • Possible duplicate of [Is Function really an Object](https://stackoverflow.com/questions/3941729/is-function-really-an-object) – garfbradaz Jul 05 '17 at 06:06

3 Answers3

1

function instances are sort of "weird" in Javascript as they are objects but their typeof is "function" and not "object".

They can however have properties added and accessed using either the syntax f.x or f["x"]. Your code simply adds a property to a function object (the value of the property is also a function, but that is irrelevant).

6502
  • 112,025
  • 15
  • 165
  • 265
  • 1
    oh okay, but when you console log an object you will be able to see all the properties and other prototypes associated with the object, whereas for this instance i was only able to see the function associated with the property. – Sri kanth Jul 05 '17 at 06:01
  • 1
    @Srikanth: indeed `Function` instances are quite strange... for example `Object.keys(f)` will return the names of all properties you added (but not predefined properties like for example `"name"`). Another weirdness is that `f.length` for example returns 0, not `undefined` and cannot be set. – 6502 Jul 05 '17 at 07:36
1

Here test1() is a property (function type) of the stringFunction var.
So you defined a function in a function object.

You can use it by invoking stringFunction.test1(); as you can invoke the outer function : stringFunction();

var stringFunction = function(){console.log("Test stringFunction")};

stringFunction.test1 = function(){
    console.log("Test 1");
}

stringFunction();
stringFunction.test1();

OUTPUT :

Test stringFunction

Test 1

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

in JavaScript every function is a Function Object. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function. In you sample the code create a property 'test1' on object stringFunction. The new property is itsealf a Function Object.

Fabiano Taioli
  • 5,270
  • 1
  • 35
  • 49