简体   繁体   English

我在警告框中获取了功能代码,为什么会这样?

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

When I run this script I get the speak function code in the alert box. 当我运行这个脚本时,我在警告框中获得了说话功能代码。 It should be "Hello!" 它应该是“你好!” not function() {alert("Hello!")}; not function(){alert(“Hello!”)}; . I use alert because I seem to like it better over console.log for learning. 我使用警报,因为我似乎更喜欢它在console.log上学习。 The script works fine without the speak function. 没有说话功能,脚本工作正常。

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);

Change the last line to 将最后一行更改为

myMother.speak();

For functions that take in strings, (like, alert() ), if you pass in a function, it will take that to mean the source code of the function. 对于接受字符串的函数(例如, alert() ),如果传入函数,则需要它来表示函数的源代码。 So, when you passed myMother.speak into alert , it took the source code, hence the result you were seeing. 因此,当您将myMother.speak传递给alert ,它会获取源代码,因此您会看到结果。

(If anyone can expand on this further or provide helpful links, feel free to edit this answer) (如果有人可以进一步扩展或提供有用的链接,请随时编辑此答案)

I get the function code in the alert box, why is this? 我在警告框中获取了功能代码,为什么会这样?

well thats cause your are referencing a function, not calling it, it seems that alert() may be calling the toString() function on the parameter, and calling tostring() on a function reference seems to be returning the source as a string, hence when you alert you get the source, Though this is just a hunch since alert seems to be implemented natively so I can't really say how its implemented. 好吧那会导致你引用一个函数,而不是调用它,似乎alert()可能正在调用参数上的toString()函数,并且在函数引用上调用tostring()似乎是将源作为字符串返回,因此当你提醒你得到消息来源时,虽然这只是一种预感,因为警报似乎是本地实现的,所以我无法真正说出它是如何实现的。

Nor can I say this behavior is consistent among all browsers. 我也不能说这种行为在所有浏览器中都是一致的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM