Home > Backend Development > PHP Tutorial > javascript - What is the scope of objects in JS? Or some questions about the properties of objects?

javascript - What is the scope of objects in JS? Or some questions about the properties of objects?

WBOY
Release: 2016-08-23 09:17:41
Original
1064 people have browsed it

<code>var a=3;
var object = { 
    a:2, 
    run: function() {
         alert(a);         //a=3;
         } 
    }; 
object.run(); </code>
Copy after login
Copy after login

Why is a not 2?
What does a:2 in the object mean?

Reply content:

<code>var a=3;
var object = { 
    a:2, 
    run: function() {
         alert(a);         //a=3;
         } 
    }; 
object.run(); </code>
Copy after login
Copy after login

Why is a not 2?
What does a:2 in the object mean?

<code>run: function() {
     this.a=1;
     } 
}; </code>
Copy after login

If you don’t specify it explicitly, it is still a variable in the global scope.

<code class="javascript">var a=3;
var object = { 
    a:2, 
    run: function() {
         alert(this.a);//2
         alert(a);//3 
        } 
    }; 
object.run(); </code>
Copy after login

The problem with scope is that if you pop up an a directly, the program will look for a at this time. It will first look for it in the current scope. If it does not find it, it will look outside, and then it will find var a. This a is actually quite As for window.a, in fact, if you directly pop up an a here, it is equivalent to finding an a under the global scope of window.a. Why is it not the a that object.a is looking for? As mentioned earlier, what you are looking for is equivalent to The scope environment of window.a instead of obejct.a is different. JS is an object-oriented programming language. Everything must have its own existence. To which thing does it belong? You need to understand this. If you don't do it, it is equivalent to acquiescing that it is global. Generally, JS owns it. Everything is defined under the window. So if you don't define which a it is first, then a is equivalent to directly belonging to the window. Of course, what is defined below the function is equivalent to belonging to the scope of the function. Not much to say in detail. Read more information.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template