Note source: Still silicon Valley latest version of the full set of JavaScript basic tutorial complete version (140 sets of actual combat teaching,JS from entry to master)_ bilibili _bilibili

[TOC]

Constructor and prototype object

1. Create objects using the factory method

function createPerson(name, age, gender){
    // Create a new object
    var obj=new Object(a);// Add attributes to the object
    obj.name = name;
    obj.age = age;
    obj.gender = gender;
    obj.sayName = function(){
        console.log(this.name);
    };
    // Return the new object
    return obj;
}

var obj1 = createPerson("Sun Wukong".1000."Male");
var obj2 = createPerson("Pig Eight Quit".3600."Male");
var obj3 = createPerson("Sha Wu Jing".10000."Male");

obj1.sayName(); / / the Monkey King
obj2.sayName(); / / pig eight quit
obj3.sayName(); / / pig eight quit
Copy the code

Any Object created using the factory method uses an Object constructor

Therefore, all the objects created are of the type Object, which makes it impossible to distinguish objects of different types

constructors

Create a constructor. The constructor that specifically creates the Person object is an ordinary function

Constructors are created in the same way as normal functions, except that constructors usually start with a capital letter constructor

The difference with ordinary function is the different way of calling

  • Normal functions are called directly
  • The constructor is requirednewKeyword to call
function Person(){
    console.log(this); // Person{}
}
// A normal function
var fun = Person();
console.log(fun); // undefined
// constructor
var person = new Person();
console.log(person); // Person{}
Copy the code

The execution flow of the constructor

  1. Create a new object immediately
  2. Sets the newly created object into a functionthisCan be used in the constructorthisTo reference the newly created object
  3. Execute the code in the function line by line
  4. Returns the newly created object as the return value
function Dog(){}function Person(name, age, gender){
    // Add attributes to the object
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.sayHello = function(){
        console.log("My'name is " + this.name + "," +
                    "I'm " + this.age + " years old, " +
                    "and I'm a " + this.gender + ".");
    };
}

var person1 = new Person("Sun Wukong".1000."man");
var person2 = new Person("Pig Eight Quit".3600."man");
var person3 = new Person("Sha Wu Jing".10000."man");
var dog = new Dog();
person1.sayHello(); // My name is Sun Wukong, I'm 1000 years old, and I'm a man.
person2.sayHello(); // My name is Zhu Bajie, I'm 3600 years old, and I'm a man.
person3.sayHello(); // My name is Sha Wujing, I'm 10000 years old, and I'm a man.
console.log(person1); // Person {name: "sun Wu kong ", age: 1000, gender: "man", sayHello: ƒ}
console.log(person2); // Person {name: "pig ", age: 3600, gender: "man", sayHello: ƒ}
console.log(person3); // Person {name: "shaowei ", age: 10000, gender: "man", sayHello: ƒ}
console.log(typeof person1); // object
console.log(typeof person2); // object
console.log(typeof person3); // object
Copy the code

Objects created using the same constructor are called class objects, and a constructor is also called a class.

The object we will create through a constructor is called an instance of this class

Use instanceof to check whether an object is an instanceof a class: the object instanceof constructor

Returns true if it is, false otherwise

console.log(person1 instanceof Person); //true
console.log(person2 instanceof Person); //true
console.log(person3 instanceof Person); //true
console.log(dog instanceof Person); 	//false
Copy the code

All objects are descendants of Object, so instanceof checks on any Object and Object return true

console.log(person1 instanceof Object); //true
console.log(person2 instanceof Object); //true
console.log(person3 instanceof Object); //true
console.log(dog instanceof Object); 	//true
Copy the code

For this:

  • When called as a function,thisiswindow
  • When called as a method, who calls the methodthisWho is the
  • When called as a constructor,thisThat’s the newly created object

Constructor modification

Create a Person constructor

In the Person constructor, a sayName method is added for each object, and so far our method is created inside the constructor

That is, the constructor creates a new sayName method every time it executes and the sayName of all instances is unique

function Person(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.sayHello = function(){
        console.log("My'name is " + this.name + "," +
                    "I'm " + this.age + " years old, " +
                    "and I'm a " + this.gender + ".");
    };
}
Copy the code

This results in the constructor creating a new method once executed, and 10,000 new methods 10,000 times executed, all of which are exactly the same

This is not necessary; it is perfectly possible to make all objects share the same method

function Person(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.sayHello = fun;
}
// Define the sayName method in global scope
function fun(){
    console.log("My'name is " + this.name + "," +
                "I'm " + this.age + " years old, " +
                "and I'm a " + this.gender + ".");
};
Copy the code

Defining functions in the global scope saves space but pollutes the namespace of the global scope

Definitions are also insecure in global scope

3. Prototype objects

Prototype prototype

For every function we create (plain or constructor), the parser adds a property prototype to the function

function Person(){}function MyClass(){}console.log(Person.prototype);
/ / {constructor: ƒ}
// 		constructor: ƒ Person()
// arguments: null
// caller: null
// length: 0
// name: "Person"
/ / prototype: {constructor: ƒ}
/ / __proto__ : ƒ ()
// [[FunctionLocation]]: 09- Prototype object.html :8
// [[Scopes]]: Scopes[1]
// __proto__: Object
console.log(Person.prototype == MyClass.prototype); // false
Copy the code

When a function calls Prototype as a normal function, it does nothing

When a function calls prototype as a constructor, it creates an object with an implied property that points to the constructor’s prototype object, which we can access via __proto__

var mc1 = new MyClass();
var mc2 = new MyClass();
var mc3 = new MyClass();
console.log(mc1.__proto__ == MyClass.prototype); // true
console.log(mc2.__proto__ == MyClass.prototype); // true
console.log(mc3.__proto__ == MyClass.prototype); // true
Copy the code

A stereotype object is a common area that can be accessed by all instances of the same class

We can set things that are common to objects in a prototype object

// Add attribute A to MyClass
MyClass.prototype.a = "123";
console.log(mc1.a);  / / 123
// Add the method sayHello to MyClass
MyClass.prototype.sayHello = function(){
alert("hello");
}
mc3.sayHello();
Copy the code

When we access a property or method of an object, it looks for it in the object itself and uses it if it has it, looks for it in the prototype object if it doesn’t, and uses it if it finds it

mc2.a = "456";
console.log(mc2.a);  / / 456
Copy the code

Later, when we create constructors, we can add the properties and methods that these objects share to the prototype object of the constructor

This allows each object to have these properties and methods without having to add them separately for each object and without affecting the global scope

hasOwnProperty

function MyClass(){

}
MyClass.prototype.name = "I'm prototype's name.";
var mc = new MyClass();
mc.age = 18;
// When you use in to check if an attribute is present in an object, it returns true if it is not present in the object but present in the prototype
console.log("name" in mc); // true
console.log("age" in mc); // true
// You can use the object's hasOwnProperty() to check whether the object itself contains this property
// This method returns true only if the object itself contains attributes
console.log(mc.hasOwnProperty("name")); // false
console.log(mc.hasOwnProperty("age"));  // true
console.log(mc.hasOwnProperty("hasOwnProperty"));  // false
Copy the code

So,hasOwnPropertyIs it a method defined in the prototype object?

Since the hasOwnProperty method is not defined in the object, it should be defined in the prototype object. Is that true?

Let’s use the hasOwnProperty method to see if hasOwnProperty itself

console.log(mc.__proto__.hasOwnProperty("hasOwnProperty"));  // false
Copy the code

There is no hasOwnProperty method in the prototype object. Where does hasOwnProperty come from?

Prototype of prototype

A stereotype object is also an object, so it also has a stereotype when we use properties or methods of an object

  • Will first look in their own, their own if there is direct use

  • If not, look for the prototype object, if yes, use it

  • If not, search for the prototype until you find the prototype of the Object

  • The prototype of an Object has no prototype. If no prototype is found in Object, undefined is returned

    console.log(mc.helloWorld);  // undefined
    Copy the code

So, following this principle, let’s use the hasOwnProperty method in the prototype

console.log(mc.__proto__.__proto__.hasOwnProperty("hasOwnProperty"));  // true
Copy the code

So if the prototype object has a prototype, does the prototype have a prototype?

Without saying a word, just print it out

console.log(mc.__proto__.__proto__.__proto__);  // null
Copy the code

According to the above principle, Mc.__proto__.__proto__ is an Object

Object objects have no archetype, but they have a __proto__ that is null

toString

When we print an object directly on the page, the event is the return value of the output object’s toString() method.

If we want to output an object without [object object], we can add a toString() method to the object

function Person(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
}
var per1 = new Person("Sun Wukong".1000."man");
var per2 = new Person("Pig Eight Quit".3600."man");
When we print an object directly on the page, the event is the return value of the output object's 'toString()' method
console.log(per1); // Person {name: "sun Wukong ", age: 1000, gender: "man"}
console.log(per1.toString()); // [object Object]
// If we want to output an object without '[object object]', we can add a 'toString()' method to the object
per1.toString = function(){
    return "Person[name=" + this.name + ", age=" + this.age + ", gender=" + this.gender + "]";
}
console.log(per1); // Person {name: "sun Wu kong ", age: 1000, gender: "man", toString: ƒ}
console.log(per1.toString()); // Person[name= sun Wukong, age=1000, gender=man]
Copy the code

The above is just modifying the toString method of per1, and does not affect other objects

If you want all objects to execute this method, you can modify the toString of the Person prototype

console.log(per2.toString()); // [object Object]
// Modify the toString of the Person prototype
Person.prototype.toString = function(){
    return "Person[name=" + this.name + ", age=" + this.age + ", gender=" + this.gender + "]";
}
console.log(per2.toString()); // Person[name= Person, age=3600, gender=man]
Copy the code

4. Garbage Collection (GC)

Just like people create garbage when they live for a long time, they also create garbage when they run a program and when too much garbage accumulates, it makes the program run too slowly

So we need a garbage collection mechanism to deal with the garbage generated during the program running

When an object doesn’t have any variables or attributes to reference it, we can never manipulate the object

In this case, this object is garbage, and this kind of too much collocation will take up a lot of memory space, causing the program to run slowly

JS has an automatic garbage collection mechanism, which will automatically destroy these garbage objects from memory. We do not need and cannot carry out garbage collection operations

All we need to do is set null for objects that are no longer used

var obj = new Object(a);// ...
obj = null
Copy the code