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.protoype ("function ()... this.first + this.middle + this.last..."). What have I done wrong here?
您需要使用()运算符调用函数:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.