0

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); 
};
  • 1
    The semantics of the named function expression are such that the name is only accessible as a variable inside the function. There's no other way to access the function by that name. This is distinct from a typical function declaration. – cookie monster Jul 15 '14 at 17:37
  • @TilwinJoy: There's no syntax error. – cookie monster Jul 15 '14 at 17:39
  • What does your second code example have to do with the first? Where are you trying to use `jjj`? – cookie monster Jul 15 '14 at 17:41
  • This has nothing to do with the fact that you're assigning the function to a prototype method. See the duplicate on what `whatName` is good for – Bergi Jul 15 '14 at 18:17

1 Answers1

-1

You do that this way:

Person.prototype.getName = function () {
    return this.name;
};

If you want to use an existing function then you do this:

Person.prototype.getName = whatName;

whatName is the name of the previous declared function

Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
  • Can you state why it is this way and rather not the other way. Because you can put a name in between function myName (). –  Jul 15 '14 at 17:37
  • whatName is a function that was declared outside of the scope of the object. –  Jul 15 '14 at 17:38
  • This doesn't really answer the question. – cookie monster Jul 15 '14 at 17:41
  • What if the method that is declared outside of the object has parameters. I will append more code to my question. –  Jul 15 '14 at 17:46