Let us say we have a function.
function Rabbit(){
console.log("shiv");
}
Now without creating an object of this function i can assign the property of this object
Rabbit.bark = function(line) {
console.log("name is", line);
};
What does this mean. do this add a variable bark to function. or does this add a property to Rabbit object, even if I am not creating an object using the new operator.
2 Answers 2
Function in JavaScript is just an object, it is called Function object.
And just like any other types of object, it has its own constructor (new Function(...)), methods (apply, bind, call...) and properties (arguments, caller, name...) . See the document.
You might be familiar with creating a function like this:
function Rabbit() {
console.log('shiv');
}
Then you should know that you can also create a function like this:
var Rabbit = new Function('console.log("shiv")');
Now, you might guess it out. If you add a new property to a Function object, as long as you don't overwrite the existing one, the function is still working just fine.
do this add a variable bark to function
- No, the function has it own closure, the only way to add variable to the function is to bind it to
thisobject usingRabbit.bind(object)
do this added a property to Rabbit object
- Well, since the "Rabbit object" is just an object, Yes.
4 Comments
Rabbit is just an object created by new Function.what does this mean. do this add a variable bark to function. or do this added a property to Rabbit object
do this add a variable bark to function - No
or do this added a property to Rabbit object - Yes
bark is a property of object of type Function
even if i am not creating an object using new operator
Rabit is already an object (of type Function). You are not creating an instance of this object, just that you are adding a property to it.
barkis a property of an object.barkis not a traditional method however, but if you addednewandprototypeinto the mix, thenbarkwould be a method of instances. as-is, there's no connection from.barkto any instance if you simply addednewto the code above, but you can reachbarkas a static method, likeArray.isArray(){name: "Rabbit", length: 0, body: "code here", arguments: [], this: {}, _closures: {}, call: function call()... }you can add new properties yourself if you'd like..call()method is how you invoke it. close enough. to be nerdy, there are internal hidden properties inside functions you can read about in the spec that you are actually calling/using, not a userland endpoint (instance method)