Is this a naming convention or function declaration
I am learning javascript and am now starting with objects and core 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");
}
whether test1 is part of stringFunction or just a naming convention. thanks in advance
source to share
Here test1()
is the property (function type) stringFunction
var.
So you have defined a function in a function object.
You can use it by calling stringFunction.test1();
as you can call an external function:stringFunction();
var stringFunction = function(){console.log("Test stringFunction")};
stringFunction.test1 = function(){
console.log("Test 1");
}
stringFunction();
stringFunction.test1();
OUTPUT:
Test stringFunction
Test 1
source to share
function
instances are "weird" in Javascript because they are objects, but theirs typeof
are "function"
not "object"
.
However, they can add and add properties using either syntax f.x
or f["x"]
. Your code is just adding a property to the object function
(the property value is also a function, but that doesn't matter).
source to share
in JavaScript, every function is a Function object. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function . In the sample code example, create a property test1 on the stringFunction object. The new property is a Function Function object.
source to share