-3

I was recently introduced into learning JavaScript and I was literally confused when I went through the prototype concepts. Everything I read and understood got confused.

Let be get straight through..

I have two questions related to functions and Objects.

Question 1:

Can functions in JS have (key, value) pair of property in it? If so, what might me the data type of the key? Because In an Object, the key of the property can be only of the types String, Object and in some special cases Symbol.

Question 2:

How are the functions evaluated internally? Are they converted to objects?

function sample () {
  // code goes here
}

and

let myFunc = new Function(,,);

Thanks

Panther Coder
  • 1,058
  • 1
  • 16
  • 43
  • 1
    i think that everything in JS is an object. So any function is an object. https://stackoverflow.com/questions/9108925/how-is-almost-everything-in-javascript-an-object – messerbill Jan 17 '18 at 13:46
  • 1
    `and understood got confused` - confusion normally indicates lack of understanding... – evolutionxbox Jan 17 '18 at 14:44

5 Answers5

2

It seems your overall question is “what are functions”.

Yes, functions are objects*. That’s why they are first-class citizens. They are just like any other value. Just like other objects they can have properties (you might be familiar with f.call, f.bind, etc).

What distinguishes functions from other objects is that they have an internal [[Call]] property (internal properties cannot be accessed from user code, they are used in the specification to define internal state/behavior of objects).

The [[Call]] property contains some representation of the code in the body of the function. It’s this code that is executed when the function is called.

There are other internal properties needed for a function to work, but [[Call]] is the most important one. It is used to determine whether an object is callable or not.

Prototypes are not primarily related to functions. Prototypes are a concept applying to objects in general. They are not very complicated either: a prototype is a just an object. What makes an object a prototype is that another object has a reference to it via its internal [[Prototype]] property. Then we can say “this object is the prototype of the other object”.


Other languages work similarly. Python for example lets you make instances of classes callable by implementing the magic def __call__: method.


*: There are seven data types in JavaScript:

  • Boolean
  • Number
  • String
  • Null
  • Undefined
  • Symbol
  • Object

The first six are so called “primitive” data types.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You can add properties at will to a function, as in JavaScript functions are objects. In both of the syntaxes you provided for creating a function, you get a (function) object.

Example of adding properties:

function counter() {
    console.log(++counter.count);
}
counter.count = 0; // create a property on the function object

// Call the function several times
counter();
counter();
counter();

As functions are objects, the same restrictions apply: property names are strings. Values can be anything. Properties are not ordered.

trincot
  • 317,000
  • 35
  • 244
  • 286
1

My best advice would be to jump into Chrome console and play there. Really good way to fit bricks in their places.

Can functions in JS have (key, value) pair of property in it? If so, what might me the data type of the key? Because In an Object, the key of the property can be only of the types String, Object and in some special cases Symbol.

Sure they can. But you misunderstood something about Object as a key. You can do this:

var obj = {};
var key = {};
obj[key] = "Smthg";

But that would work just because key would be stringified. So obj[key] would be converted into obj["[object Object]"]. Test it out:

var obj = {};
var key = {};
obj[key] = "key1";
obj["[object Object]"] = 'key2';

console.log(obj[key]);

As you see, no matter how many objects you will use as a key - they will override each other.

How are the functions evaluated internally? Are they converted to objects?

JS is OOP language - everything is an object (except some primitives etc.). So that means there are many different objects. And they inherit something from each other, otherwise there would be a one GIANT object with all those properties bounded and endless waiting time to load your first "Hello World" application.

My probably best tool to learn JS, after taking some readings is console.dir() method (or just dir(someVar) if in console mode).

Create object - var f = new Function() and dir(f) to see what is it and what is its prototype etc.

Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81
1

Answer to Question 1:

Yes, you can have key: value pair inside a function, but that function is called constructor. For example:

function Car(make, model, year) {
   this.make = make;
   this.model = model;
   this.year = year;
}

In ES6: you can store similar key:value pair using constructor() function inside a class. For example:

 constructor(make, modal, year) { // constructor syntactic sugar
   this.make = make;
   this.model = model;
   this.year = year;
}

The data-type of key depends on what type of value you're storing in that key. In our example, if I store string value in this.model, data-type of model key would be string and If I store year as a number then data-type of this.year would be number.

Answer to Question 2

To understand how a function works internally, you need to understand execution context. To understand execution context, you must read this article by David. To simply put:

Every time a function is called, a new execution context is created. However, inside the JavaScript interpreter, every call to an execution context has 2 stages:

Creation Stage

[when the function is called, but before it executes any code inside]: Create the Scope Chain. Create variables, functions and arguments. Determine the value of "this".

Activation / Code

Execution Stage: Assign values, references to functions and interpret / execute code.

Abhishek Raj
  • 107
  • 1
  • 3
  • 10
0

Now its a good question , which can confuse many. First thing there is the concept of constructor and prototype in javascript So

function A() {
console.log("A")
}

if you console.log(typeof(A)) // "function"

now A has also a protoype

console.log("Aprototype", A.prototype) 

that will be an object That native object has a property proto

console.log(A.prototype.__proto__)

This will be parent prototype. from which the current prototype is inheriting. This parent prototype will also have a constructor, That is your Function constructor

console.log("parentConstructor", A.prototype.__proto__.constructor)

Now this parent Protype has also one more proto, which is linked to Object function constructor

console.log("parent parent __proto__", A.prototype.__proto__.__proto__)

and its constructor is your Object constructor function.

Thats why you are able to get new object

var t = new Object()

Look how we have called it like constructor.

Thats how prototypical javascript is :)

simbathesailor
  • 3,681
  • 2
  • 19
  • 30