为什么javascript构造函数会打印传递给它的参数? [英] Why does javascript constructor prints the argument passed to it?

查看:69
本文介绍了为什么javascript构造函数会打印传递给它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道javascript中构造函数的内部工作。

这就是我要面对的事情-
让我们假设一个类A

  A类{
constructor(){}
}

现在在控制台中运行命令

  A.constructor('alert ( Hi)')

此命令将打印

 ƒAnonymous(){
alert( Hi)
}

为什么它不显示完整的初始化或我遗漏了什么?



这会导致在我们运行时执行警报

  A.constructor('alert( Hi)')()

尽管运行此

  A.constructor()(' alert( Hi)')

不执行警报。



我完全感到困惑,因此想知道构造函数是如何解释事物的。

解决方案

1。



  A.constructor('alert( Hi)')

由于 A 是一个类(=函数),所以 A.constructor 是内置的 Function 构造函数,此代码与


$ b相同$ b

  Function('alert( Hi)')

  function(){alert( Hi)} 

,即具有主体 alert( Hi)的匿名函数。控制台正是显示该内容。



2。



  A.constructor ('alert( Hi)')()

$相同b
$ b

  Function('alert( Hi)')()

 (function(){alert( Hi)})( )

也就是说,正在调用新创建的函数并显示警报。



3。



  A.constructor()('alert( Hi)' )

A.constructor Function Function()创建一个没有主体的匿名函数,因此我们有:

 (function(){})('alert( Hi)')

正在使用参数 alert( Hi)调用该函数,但是由于它没有主体,所以什么也没发生。 / p>

I wanted to know the internal working of the constructor in javascript.
So here is what I am facing- Let us assume a class A

class A {
constructor(){}
}

Now when I run the the command in console

A.constructor('alert("Hi")')

This commands prints

ƒ anonymous() {
 alert("Hi")
 }

Why does it not show complete initialisation or am I missing something?

This leads alert to execute when we run

A.constructor('alert("Hi")')()

Though running this

A.constructor()('alert("Hi")')

does not execute the alert.

I am totally confused and hence want to know how constructor interpret things.

解决方案

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.

这篇关于为什么javascript构造函数会打印传递给它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆