我在警报框中得到了功能代码,为什么会这样

I get the function code in the alert box, why is this?

本文关键字:代码 功能 为什么      更新时间:2024-05-29

当我运行此脚本时,我会在警报框中获得speak函数代码。它应该是"Hello!"而不是函数(){alert("Hello")}。我使用alert是因为我似乎更喜欢它而不是console.log。脚本在没有发言功能的情况下运行良好。

function person(firstname,lastname,age,eyecolor) {
  this.firstname=firstname;
  this.lastname=lastname;
  this.age=age;
  this.eyecolor=eyecolor;
  this.newlastname=newlastname;
  this.speak=function(){alert("Hello!")};
}
var myFather=new person("John", "Doe", 45, "blue");
var myMother=new person("Sally","Rally", 48,"green");
function newlastname(new_lastname) {
  this.lastname=new_lastname;
}
myMother.newlastname("Doe");
alert(myMother.lastname);
alert(myMother.speak);

将最后一行更改为

myMother.speak();

对于接收字符串的函数(如alert()),如果传入一个函数,则表示该函数的源代码。因此,当您将myMother.speak传递到alert时,它获取了源代码,因此您看到了结果。

(如果有人可以进一步扩展或提供有用的链接,请随时编辑此答案)

我在警报框中得到了功能代码,为什么会这样?

这是因为你引用了一个函数,而不是调用它,似乎alert()可能在参数上调用了toString()函数,而在函数引用上调用tostring()似乎是以字符串的形式返回源,因此当你发出警报时,你会得到源,尽管这只是一种预感,因为警报似乎是本地实现的,所以我真的不能说它是如何实现的。

我也不能说这种行为在所有浏览器中都是一致的。