If I create an object in JavaScript and then add a function with the prototype
keyword, why can the two names not be different?
I have the function named getName
and another named whatName
. I cannot call whatName
without an error. What is the difference between naming a function and an anonymous function?
Which is the more preferred way of doing this?
Code:
Person.prototype.getName = function whatName() {
return this.name;
};
Code:
<script>
var Person = function Person(n,f,m,l) {
this.name = n;
this.lname = l;
this.fname = f;
this.mname = m;
this.callMeth1 = function jjj() {
}
this.callMeth2 = function () {
}
this.callMeth3 = function () {
}
};
Person.prototype.getName = function () {
return this.name;
};
var test = new Person("Doug");
Person.prototype.sayMyName = function() {
alert('Hello, my name is ' + this.getName());
};
test.sayMyName();
</script>
Code:
function callMyMeth4 (a,b) {
var aaa = a;
var bbb = b;
}
var Person = function Person(n,f,m,l) {
this.name = n;
this.lname = l;
this.fname = f;
this.mname = m;
this.callMeth1 = function () {
}
this.callMeth2 = function () {
}
this.callMeth3 = function () {
}
this.callMeth3 = callMyMeth4(a,b);
};