The js class encapsulates common methods

   /*1. 
2. 
3.prototype */ 
   var person = function(){
         var age = 22;
         function showName(){
             console.log(this.name)
         };
         this.show = function(){
             console.log(this.name);
             showName(); 
         }
   }
   person.prototype.setname = function(str){
     name = str;     
   }
   var p1 = new person();
   p1.setname("");
   p1.show();
   console.log(p1.age);//undefined

Why is the this.name under the this.show method undefiend, and the this.name under the showName method Dabao?

Mar.04,2021
Don't think about the problem pointed to by
thisthis

var person = function(){
         var age = 22;
         function showName(){
             console.log(this)
         };
         this.show = function(){
             console.log(this);
             showName(); 
         }
   }
   person.prototype.setname = function(str){
     name = str;     
   }
   var p1 = new person();
   p1.setname("");
   p1.show();
   console.log(p1.age);

this.
this.show,this points to p1Magol p1 and has no name attribute.
showName () is called directly, pointing to window.

Menu