When I run this script I get the speak function code in the alert box. It should be “Hello!” not function() {alert(“Hello!”)}; . I use alert because I seem to like it better over console.log for learning. 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
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 passedmyMother.speakintoalert, 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)