我在警告框中获得了功能代码,为什么?

问题描述:

当我运行这个脚本时,我在警告框中获得说话功能代码。应该是“你好!”不是function(){alert(“Hello!”)}; 。我使用警报,因为我似乎更喜欢使用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.speakalert时,它采用了源代码,因此你看到了结果。

(如果任何人都可以在此展开进一步或提供有用的链接,随意编辑这个答案)

+0

谢谢,我也拿出了警报,并用myMother.speak()替换了它。因为这是双重警报。再次感谢你 – 2012-07-31 00:41:35

+1

是的,我意识到,所以我改变了答案,以避免双重警报。 – 2012-07-31 00:42:27

+1

您可能会对此进行扩展,以解释为什么,对于未来发现它的新JS程序员。 – 2012-07-31 00:50:15

我得到的警告框的功能代码,这是为什么?

以及多数民众赞成原因您正在引用的函数,而不是调用它,它似乎alert()可调用的参数toString()功能,并且在函数引用调用tostring()似乎返回源为一个字符串,因此当你提醒你获得源代码时,虽然这只是一种预感,因为警报似乎是在本地实现的,所以我不能说它是如何实现的。

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