1

このスクリプトを実行すると、アラート ボックスに音声機能コードが表示されます。「こんにちは!」のはずです。function() {alert("Hello!")}; ではありません。. 学習には console.log よりも良いように思われるため、アラートを使用します。スクリプトは、speak 関数がなくても正常に機能します。

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

2 に答える 2

3

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. So, when you passed myMother.speak into alert, it took the source code, hence the result you were seeing.

(If anyone can expand on this further or provide helpful links, feel free to edit this answer)

于 2012-07-31T00:38:48.277 に答える
1

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.

Nor can I say this behavior is consistent among all browsers.

于 2012-07-31T00:49:36.560 に答える