I'm practicing object oriented syntax in javascript and am having some problems. This is my code:
<html>
<head>
<script type="text/javascript">
function Name(first,mid,last) {
this.first = first;
this.middle = mid;
this.last = last;
}
Name.prototype.fullname = function () {
return this.first + " " + this.middle + " " + this.last;
}
Name.prototype.fullnamereversed = function() {
return this.last + " " + this.middle + " " + this.first;
}
var s = new Name("James","Harlow","Smith")
</script>
</head>
<body>
<script type="text/javascript">
document.body.innerHTML = s.fullname;
document.body.innerHTML = s.fullnamereversed;
</script>
</body>
</html>
When I load the page, the innerHTML of the body is the exact text of Name开发者_JS百科.protoype ("function ()... this.first + this.middle + this.last..."). What have I done wrong here?
You need to call the functions with the () operator:
document.body.innerHtml = s.fullname();
You are assigning a function to the prototype, therefore you need to call it as such:
<script type="text/javascript">
document.body.innerHTML = s.fullname() + ' ' + s.fullnamereversed();
</script>
You need to invoke your function: document.body.innerHTML = s.fullname();
Example here.
document.body.innerHTML = s.fullname;
sets the innerHTML to the function s.fullname
.
If you want to set the innerHTML to what the function returns, then you need to actually call the function:
document.body.innerHTML = s.fullname();
精彩评论