JavaScript note 5 (scope, declaration in advance, this, create an object and constructor using factory method, prototype object, toString(), garbage collection)

Posted by wyred on Tue, 22 Feb 2022 16:18:20 +0100


  • Scope refers to the scope of a variable
  • There are two scopes in JS

1. Global scope

  • The JS code written directly in the script tag is in the global scope

  • Global scopes are created when the page is open and destroyed when the page is closed

  • There is a global object window in the global scope, which represents a browser window. It is created by the browser and can be used directly

  • In the global scope:
    (1) The created variables are saved as the properties of the window object
    (2) The functions created will be saved as methods of window objects

  • Variables in the global scope are global variables, which can be accessed in any part of the page

2. Function scope

  • The function scope created when calling the function. After the function is executed, the function scope is destroyed
  • Each time a function is called, a new function scope will be created, which are independent of each other
  • Variables in the global scope can be accessed in the function scope, but variables in the function scope cannot be accessed in the global scope
  • When operating a variable in the scope of a function, it will first look for it in its own scope and use it directly if there is one; If not, search for the upper level scope until the global scope is found; If it is still not found in the global scope, an error ReferenceError will be reported
  • The function scope also has the feature of declaration in advance. Variables declared with var keyword will be declared before all code in the function is executed; Function declarations are also executed before all code in the function is executed
  • In a function, variables that are not declared with var become global variables
function fun() {
d = 100;//If no var declaration is used, it will be set as a global variable
  • Defining formal parameters is equivalent to declaring variables in the function scope
function fun(e) {//Declared e
e = 55;

Statement in advance

1. Declaration of variables in advance

  • Variables declared with the var keyword will be declared before all code is executed (but will not be assigned). However, if the var keyword is not used when declaring variables, the variables will not be declared

2. Declaration of function in advance

  • Using function declaration form to create function function function () {}, it will be created before all code is executed, so we can call function before function. Functions created using function expressions are not declared ahead of schedule, so they cannot be called before declarations.
function fun(){
alert("I'm code");
fun();//It can be placed in front of function
var fun = function(){
alert("I'm code");
fun();//It cannot be placed in front of function


  • When calling a function, the parser will pass an implicit parameter to the function every time. This parameter is this, which refers to an object. This object is called the context object of function execution
  • this points to different objects according to different function call methods
    (1) When called as a function, this is always window
    (2) When called as a method, this is the object that calls the method
var name = "overall situation";
function fun(){
var obj = {
name: "Sun WuKong";
sayName: fun
var name = "Global name attribute";
fun();//The global attribute (name) is displayed instead of the global attribute (1)
//fun() and window fun() consistent
obj.sayName();//If it meets (2), "Monkey King" will be displayed

Create an object and constructor using factory methods

1. - through this method, objects can be created in large quantities

function creatPreson(name , age , gender){//Creator's object
var obj = new Object();//Create a new object = name;
obj.age = age;
obj.gender = gender;
obj.sayName = function(){
return obj;
 var obj2 = creatPreson("Zhu Bajie", 28, "male"); 
 var obj3 = creatPerson("Baigujing" , 18 , "female");

function creatDog(name , age){//Create a dog object
var obj = new Object(); = name;
obj.age = age;
obj.sayHello = function(){
var dog = creatDog("Wangcai" , 3);

  • It is known from the above code that the objects created by the factory method and the constructors are all objects, so we can't distinguish many different types; We need to use our constructor

2. Constructor

  • The constructor is an ordinary function. The creation method is no different from that of ordinary functions. The difference is that the constructor is used to capitalize the first letter
  • The difference between constructors and ordinary functions is that they are called in different ways: ordinary functions are called directly, while constructors need the new keyword to call
  • Create a constructor to create a Person object
function Person(name , age){ = name;
this.age = age;
this.sayName = function(){//Add a method to the object
function Dog(name , age){ = name;
this.age = age;
var per = new Person("Sun WuKong" ,18);//new is important
var dog = new Dog("Wangcai" , 3);
console.log(dog);//The two types can be distinguished
  • Execution flow of constructor
    (1) Create a new object immediately
    (2) Set the object to this in the function. You can use this in the constructor to reference the newly created object
    (3) Execute the code in the function line by line
    (4) Returns the newly created object as a return value

  • Use instanceof to check the instance of a class
    (1) For example, the above per is an example of Person
    (2) Syntax: object instanceof constructor
    (3) If it returns true, it does not return false

console.log(per instanceof Person);//true
console.log(dog instanceof Person);//false
console.log(per instanceof Object);//true
console.log(dog instanceof Object);//true
  • All objects are descendants of Object, so any Object and Object will return true when they are checked by instanceof


Solution: define the method in the global scope

function Person(name , age){ = name;
this.age = age;
this.sayName = fun;
function fun(){
var per = new Person("Sun WuKong" ,18);
var per2 = new person("Zhu Bajie" , 38);

Disadvantages: defining functions in the global scope pollutes the namespace of the global scope, and it is not safe to define them in the global scope; This uses prototype objects

Prototype object

1. prototype

  • For each function we create, the parser will add an attribute prototype to the function, which corresponds to an object, which is what we call the prototype object
  • If a function calls prototype as a normal function, it has no effect
  • When a function is called in the form of a constructor, the object it creates will have an implicit attribute pointing to the prototype object of the constructor_ proto_ To access this property
  • The prototype function is equivalent to a public area. All instances of the same class can access the prototype object. We can uniformly set the common contents in the object into the prototype object.
  • When we access a property or method of an object, it will first look in the object. If it is directly used, if not, it will look in the prototype object. If it is found, it will be used directly
  • In the future, when we create constructors, we can uniformly add the common properties and methods of these objects to the prototype object of the function, so that each object can have these properties and methods without adding them separately for each object and affecting the global scope
function MyClass(){
MyClass.prototype.a = 123;//Add attribute a to the prototype of MyClass
MyClass.prototype.sayName = function(){
};//Add a method to the prototype of MyClass
var mc = new MyClass();
var mc2 = new MyClass();
//console.log(mc2._proto_); Access implicit properties
mc.a = "I am mc Medium a";//Add a attribute to mc

  • When using in to check an object, if there is no in the object but there is in the prototype, it will also return true
function MyClass(){
} = "I";//Add a name attribute to the prototype of MyClass
var mc = new MyClass();
console.log("name" in mc);//true
  • You can use the object's hasOwnproperty() to check whether the object itself contains this property; Using this method, you can return true only if the object itself contains attributes
Carry on
mc.age = 18;


  • The prototype Object is also an Object, so it also has a prototype. When we use an Object's attribute or method, we will first look for it in ourselves. If we have it, we will use it directly. If not, we will look for it in the prototype Object. If there is one in the prototype Object, we will use it. If not, we will go to the prototype of the prototype until we find the prototype of the Object object, The prototype of the Object object has no prototype. If it is still not found in the Object, it returns undefined


  • When we print an object in the page, it is actually the return value of the toString() method of the output object
  • If we want to output the object without outputting [object object], we can add a toString() method to the object
function Person(name , age , gender){ = name;
this.age = age;
this.gender = gender;
//Modify toString of Person prototype
Person.prototype.toString = function(){
return "Person[name="",age="+this.age+",gender="+this.gender+"]"};
//Create a Person instance
var per = new Person("Sun WuKong" , 18 , "male");

Garbage collection (GC)

  • Just like garbage will be generated when living for a long time, garbage will also be generated when running the program. When these garbage accumulate too much, it will lead to too slow running of the program. Therefore, we need a garbage collection mechanism to deal with the garbage generated during the running of the program
  • When an object does not have any variables or attributes to reference it, we will never be able to operate the object. At this time, this object is garbage. Too many objects will occupy a lot of memory space and slow down the program, so this garbage must be cleaned up
  • There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory. We don't need and can't garbage collection
  • All we need to do is set the object that is not in use to null
var obj = new Object();
obj = null;

Topics: Javascript Front-end