Kevin
Kevin

Reputation: 23634

Difference between private and privileged method

Let's suppose i have a class like this.

function kevin(name){
   this.name = name;
   this.methodKevin = function(){
        console.log(this.name);
   };
   var kevin = function(){
        console.log(this.name); 
   }
   function newKevin(){
        console.log(this.name);
   }
}
  1. What is the difference between them in javascript?.
  2. Is my class perfect, can i have a function expression inside my constructor?

Upvotes: 1

Views: 107

Answers (1)

Trent Earl
Trent Earl

Reputation: 3607

It depends on how they are called, and maybe confusing to talk about since there are two functions named: kevin.

  1. methodKevin will be bound to the window object unless called by new kevin, in whichcase it be bound to the top level kevin function object. this.name will be as expected only work if called by a function instantiated with new.
  2. var kevin is function scoped to the parent kevin funciton, so that it may never be called outside that function. It is private in that sense. this.name will work, but name alone will suffice.
  3. same as 2

Upvotes: 2

Related Questions