problem with frisking this

0

Good I am the following code that I have taken it from this page this particular example:

var myApp = function(){
     var that = this;
     var name = "World";
     var sayHello = function(){
         console.log( 'Hello, ' + that.name );
 }; 
sayHello(); 
};
myApp();  

It is assumed that when I call the function this refers to the object itself so when saving in the variable that , the value of the object is saved and then in console that has access to name , but when I debug this keeps pointing to the object window . If someone can tell me what happens and why. I would appreciate it.

    
asked by Ronald Sanchez 02.02.2018 в 19:20
source

1 answer

2

For a function to have access to its own scope using this , you have to initialize it using the operator new . This is because when you execute a function in a normal way, the default scope is Window which is what happens in your case.

It is also good to note that in your example you have the error that you declared the variable name private, so that this can find it, you have to add it to the object as this.nombrePropiedad :

var myApp = function(){
     var that = this;

     // var name no define la propiedad en el ambito this 
     // mientras que this.name si la define en ella.
     this.name = "World";
     var sayHello = function(){
         console.log( 'Hello, ' + that.name );
 }; 
sayHello(); 
};
new myApp();
    
answered by 02.02.2018 / 19:42
source