Why Does Javascript Constructor Prints The Argument Passed To It?
Solution 1:
1.
A.constructor('alert("Hi")')
Since A
is a class (=a function), A.constructor
is the built-in Function
constructor, and this code is the same as
Function('alert("Hi")')
or
function () { alert("Hi") }
that is, an anonymous function with the body alert("Hi")
. The console displays exactly that.
2.
A.constructor('alert("Hi")')()
is the same as
Function('alert("Hi")')()
or
( function() { alert("Hi") } ) ()
that is, the newly created function is being called and displays an alert.
3.
A.constructor()('alert("Hi")')
A.constructor
is Function
, and Function()
creates an anonymous function with no body, so we have:
( function() {} ) ('alert("Hi")')
The function is being called with an argument alert("Hi")
, but since is has no body, nothing happens.
Solution 2:
When you write A.constructor()
, you are not actually calling the constructor of class A that you defined in class A, you are accessing the Object.prototype.constructor of A. What Object.prototype.constructor does? It returns the reference to the constructor which was used to create A.
As A is a class and class is a function in javascript, A.constructor
returns reference to Function
i.e. So A.constructor
is equivalent to Function
.
As Function("alert('hi')")
in javascript is equivalent to ƒ anonymous( ) { alert('hi') }
, A.construtor("alert('hi')")
is equivalent to ƒ anonymous( ) { alert('hi') }
.
So it means A.construtor("alert('hi')")
returns a reference to function i.e. ƒ anonymous( ) { alert('hi') }
, so that answers 1st part of your question.
Now how do you call function in javascript? You use the parenthesis after the function reference. As A.constructor("alert('hi')")
returns function reference, you can call that function using A.constructor("alert('hi')")()
which executes the alert. That answers the 2nd part of your question.
In the third part i.e. A.constructor()('alert("Hi")')
, first, A.constructor()
returns ƒ anonymous( ) {}
, which you are calling providing parenthesis in front if it i.e. ('alert("Hi")'
but as this function is empty, nothing happens while calling it. So that answers the 3rd part of your question.
Hope it clarifies the confusion.
Post a Comment for "Why Does Javascript Constructor Prints The Argument Passed To It?"