JS object of front-end learning notes

object-oriented

Cognitive object

Cognitive object

  • An object is a collection of "key value pairs", which represents the mapping relationship between attributes and values

Object syntax

  • k and v are separated by colons, and each group of k:v is separated by commas. Commas can not be written after the last k:v pair

  • If the property key name of an object does not conform to the JS identifier naming convention, the key name must be enclosed in quotation marks

  • You can use point syntax to access the value of a specified key in an object
xiaoming.name; // 'Xiao Ming'
xiaoming.age; // 12
xiaoming.hobbys; // ['football', 'swimming', 'programming']
// Object to access its properties
  • If the attribute name does not conform to the JS identifier naming convention, it must be accessed in square brackets
// If the identifier naming convention is not met, the attribute must be accessed with square brackets
xiaoming['favorite-book']; // 'schuck and beta '
  • If the property name is stored as a variable, it must be in square brackets
var obj = {
    a: 1,
    b: 2,
    c: 3
};
//Attribute names are stored in variables
var key = 'b';
console.log(obj.key); //undefined
console.log(obj[key]);// 2
console.log(obj.b); //2
  • You can change an attribute by reassigning it directly using the assignment operator
var obj = {
    a: 10
};
obj.a = 30;
obj.a++;
  • If the object itself does not have a property value, this property will be created when it is assigned with dot syntax
var obj = {
	a: 10
};
obj.b = 40;
  • If you want to delete the attributes of an object, you need to use the delete operator
var obj = {
    a: 1,
    b: 2
};
delete obj.a;

Object method

  • If a property value is a function, it is also called the "method" of the object
var xiaoming = {
    name: 'Xiao Ming',
    age: 12,
    sex: 'male',
    hobbys: ['Football', 'Swimming', 'programming'],
    'favorite-book': 'Schunck and betta',
    sayHello: function () {
        console.log('Hello, I'm Xiao Ming. I'm 12 years old. I'm a boy');
    }
};
  • Use point syntax to call methods on objects
xiaoming.sayHello();
  • Methods are also functions, but methods are "function properties" of objects, which need to be called with objects
  • After formally learning what is "method", we can deeply understand the writing forms of some functions we learned before, such as:
console.log();
Math.ceil();

Traversal of objects

  • Similar to traversing arrays, objects can also be traversed. Traversing objects requires a for... in... Loop
  • Use the for... in... Loop to traverse each key of the object
  • In the subsequent ES6 related courses, we will also learn the new way of object traversal

Deep and shallow cloning of objects

  • Basic and reference types

  • Object is a reference type value, which means:
    • You cannot clone an object with a syntax like var obj2 = obj1
    • When using = = or = = = to compare objects, we compare whether they are the same object in memory, not whether the values are the same

Shallow cloning of objects

  • Review what is shallow cloning: only the "surface layer" of the object is cloned. If some attribute values of the object are reference type values, they are not cloned further, but their references are passed.
  • Shallow cloning of objects can be achieved by using the for... in... Loop
var obj1 = {
    a: 1,
    b: 2,
    c: [44, 55, 66]
};

// Implement shallow cloning
var obj2 = {};
for (var k in obj1) {
    // Every time a k attribute is traversed, a k attribute with the same name is added to obj2
    // The value is the same as the k attribute value of obj1
    obj2[k] = obj1[k];
}

// Why shallow cloning? For example, if the value of the c attribute is a reference type value, the c attributes of obj1 and obj2 are essentially the same array in memory and have not been cloned.
obj1.c.push(77);
console.log(obj2);                  // The c attribute of obj2 will also be added to the array
console.log(obj1.c == obj2.c);      // True, true proves that the array is the same object

Deep cloning of objects

  • Review what deep cloning is: clone the whole picture of objects. You can clone objects regardless of whether their attribute values are reference type values or not
  • Similar to deep cloning of arrays, deep cloning of objects requires recursion
var obj1 = {
    a: 1,
    b: 2,
    c: [33, 44, {
        m: 55,
        n: 66,
        p: [77, 88]
    }]
};

// Deep cloning
function deepClone(o) {
    // To determine whether o is an object or an array
    if (Array.isArray(o)) {
        // array
        var result = [];
        for (var i = 0; i < o.length; i++) {
            result.push(deepClone(o[i]));
        }
    } else if (typeof o == 'object') {
        // object
        var result = {};
        for (var k in o) {
            result[k] = deepClone(o[k]);
        }
    } else {
        // Basic type value
        var result = o;
    }
    return result;
}


var obj2 = deepClone(obj1);
console.log(obj2);

console.log(obj1.c == obj2.c);     // false

obj1.c.push(99);
console.log(obj2);                 // obj2 remains unchanged, because there is no "broken ties" phenomenon

obj1.c[2].p.push(999);
console.log(obj2);                 // obj2 remains unchanged, because there is no "broken ties" phenomenon

Cognitive context

Context of function

  • You can use the this keyword in a function, which represents the context of the function
  • Similar to "this" in Chinese, the specific meaning of this in the function must be judged by the "preface and postscript" when calling the function

this in function

var xiaoming = {
    nickname : 'Xiao Ming',
    age : 12,
    sayHello : function () {
    	console.log('I am' + this.nickname + ',I' + this.age + 'Years old');
    }
};
xiaoming.sayHello(); //I'm Xiao Ming. I'm 12 years old

The context of a function is determined by how it is called

  • If the same function is called in different forms, the context of the function is different

    • Case 1: the object management calls the function, and this in the function refers to the managed object

      • xiaoming.sayHello();
    • Case 2: parentheses directly call the function, and this in the function refers to the window object

      • var sayHello = xiaoming.sayHello;
        sayHello();
        
  • The reference of this cannot be determined when the function is not called

  • Only when a function is called can its context be determined

var obj = {
    a: 1,
    b: 2,
    fn: function () {
    	console.log(this.a + this.b);
    }
};

var obj = {
    a: 1,
    b: 2,
    fn: function () {
    	console.log(this.a + this.b);
    }
};
obj.fn(); //3

var fn = obj.fn;
fn(); //NaN

Context rules

The context of a function is determined by how the function is called

  • The context of a function (this keyword) is determined by how the function is called. Function is the "runtime context" policy
  • If the function is not called, the context of the function cannot be determined

Context rule 1

  • Rule 1: if an object calls its method function, the context of the function is the object of the management
Object Method ()
//Case 1
function fn() {
	console.log(this.a + this.b);
}
var obj = {
    a: 66,
    b: 33,
    fn: fn
};
obj.fn();  //99

//Case 2
var obj1 = {
    a: 1,
    b: 2,
    fn: function () {
    	console.log(this.a + this.b);
    }
};
var obj2 = {
    a: 3,
    b: 4,
    fn: obj1.fn
};
obj2.fn(); // 7

//Case 3
function outer() {
    var a = 11;
    var b = 22;
    return {
        a: 33,
        b: 44,
        fn: function () {
        	console.log(this.a + this.b);
        }
    };
}
outer().fn();  //77

//Case 4
function fun() {
console.log(this.a + this.b);
}
var obj = {
    a: 1,
    b: 2,
    c: [{
        a: 3,
        b: 4,
        c: fun
    }]
};
var a = 5;
obj.c[0].c(); //7

Context rule 2

  • Rule 2: if the parentheses call the function directly, the context of the function is the window object
Function ()
//Case1
var obj1 = {
    a: 1,
    b: 2,
    fn: function () {
    	console.log(this.a + this.b);
    }
};
var a = 3;
var b = 4;
var fn = obj1.fn;
fn(); // 7

//Case2:
function fun() {
	return this.a + this.b;
}
var a = 1;
var b = 2;
var obj = {
    a: 3,
    b: fun(), //Applicable rule 2
    fun: fun
};
var result = obj.fun(); //Applicable rule 1
console.log(result);

Context rule 3

  • Rule 3: the array (class array object) is called by a function, and the context is this array (class array object)
  • What is a class array object: all objects whose key names are natural number sequences (starting from 0) and have the length attribute
  • The arguments object is the most common class array object, which is a list of arguments to a function
Array [subscript] ()
//case1:
var arr = ['A', 'B', 'C', function () {
	console.log(this[0]);
}];
arr[3](); //"A"

//Case2
function fun() {
	arguments[3]();
}
fun('A', 'B', 'C', function () {
	console.log(this[1]);
}); //"B"

Context rule 4

  • Rule 4: for functions in IIFE, the context is a window object
(function() {})();
//Case1
var a = 1;
var obj = {
    a: 2,
    fun: (function () {
        var a = this.a; //1
        return function () {
       		console.log(a + this.a); //this.a=2
    }
    })()
};
obj.fun(); //3

Context rule 5

Rule 5: the timer and delayer call the function, and the context is the window object

Setinterval (function, time); SetTimeout (function, time);
var obj = {
    a: 1,
    b: 2,
    fun: function () {
    	console.log(this.a + this.b);
    }
}
var a = 3;
var b = 4;
setTimeout(obj.fun, 2000); //7

//Case2
var obj = {
    a: 1,
    b: 2,
    fun: function () {
    	console.log(this.a + this.b); //Applicable rule 1
    }
}
var a = 3;
var b = 4;

setTimeout(function() {
	obj.fun();
}, 2000); //3. Note that the difference between this case and case1 is that the fun here is called directly by obj, not by the delayer

Context rule 6

Rule 6: the context of the event handler is the DOM element that binds the event

DOM element onclick = function () {};
  • Please achieve the effect: click which box, which box will turn red. It is required to use the same event handler function
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
       #box1{
           border: 1px solid #000;
           width: 100px; height: 100px;
           float: left;
           margin-left: 20px;
       } 
       #box2{
           border: 1px solid #000;
           width: 100px; height: 100px;
           float: left;
           margin-left: 20px;
       } 
       #box3{
           border: 1px solid #000;
           width: 100px; height: 100px;
           float: left;
           margin-left: 20px;
       } 

       #box4{
           border: 1px solid #000;
           width: 100px; height: 100px;
           float: left;
           margin-left: 20px;
       } 
    </style>
</head>
<body>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
    <div id="box4"></div>
    <script>
        function setColorToRed(){
            //Backup context
            var self = this;
            setTimeout(function(){
                self.style.backgroundColor= 'red';
            },2000);
        }

        var box1 = document.getElementById("box1");
        var box2 = document.getElementById("box2");
        var box3 = document.getElementById("box3");
        var box4 = document.getElementById("box4");

        box1.onclick = setColorToRed;
        box2.onclick = setColorToRed;
        box3.onclick = setColorToRed;

        function setColorToRed1(o){
            o.style.backgroundColor = 'red';
        }
        box4.onclick = function(){
            setColorToRed1(box4);
        }

    </script>
</body>
</html>
var obj = {
    a: 1,
    b: 2,
    fn: function() {
        console.log(this.a + this.b);
        console.log(this === window);
    }
};

var a = 4;
var b = 9;

obj.fn(); //3 False [this===obj] true
var fn = obj.fn;
fn(); //13 True

call and apply

call and apply can specify context

function sum() {
	alert(this.chinese + this.math + this.english);
}
var xiaoming = {
    chinese: 80,
    math: 95,
    english: 93
};
sum.all(xiaoming);
sum.apply(xiaoming);

The difference between call and apply

function sum(b1, b2) {
	alert(this.c + this.m + this.e + b1 + b2);
}
var xiaoming = {
    c: 80,
    m: 95,
    e: 93
};
sum.call(xiaoming, 5, 3);
sum.apply(xiaoming, [5, 3]);
function sum(){
    alert(this.a+this.b+this.c);
}
function sum1(b1,b2){
    alert(this.a+this.b+this.c+b1+b2);
}

var tom = {
    a:100,
    b:90,
    c:95
}
var jack = {
    a:100,
    b:90,
    c:95,
    sum:sum,
}
jack.sum();
sum.call(tom);
sum.apply(tom);
sum1.call(tom,90,80);   //When call accepts parameters 
sum1.apply(tom,[90,98]);

function fun1(){
    fun2.apply(this,arguments); 
}
function fun2(a,b){
    alert(a+b);
}
fun1(34,43); //77 if called directly here, this will point to the windows object

Context rule summary

rulecontext
Object Function ()object
Function ()window
Array [subscript] ()array
IIFEwindow
timerwindow
DOM event handlerBinding DOM elements
call and applyArbitrary designation

Constructor

Call the function with new in four steps

  • Now let's learn a new way to call a function: the new function ()

  • You may know that the new operator is closely related to "Object-Oriented", but now, let's not discuss its "Object-Oriented" meaning, but first clarify the execution steps and context of calling the function with new.

  • JS stipulates that calling a function using the new operator will carry out "four steps":

    • A blank object is automatically created in the function body
    • The context of the function (this) points to this object
    • The statements in the function body are executed
    • The function automatically returns the context object, even if the function does not have a return statement
  • Four step explanation

function fun() {
    this.a = 3;
    this.b = 5;
}
var obj = new fun();
console.log(obj);

Step 4 - step 1

  • Step 1: a blank object will be automatically created in the function body

Step 4 - step 2

  • Step 2: the context of the function (this) will point to this object

Step 4 - step 3

Step 3: execute the statement in the function body

Step 4 - step 4

  • Step 4: the function will automatically return the context object, even if the function does not have a return statement

Constructor

What is a constructor

  • Let's make a small improvement on the previously written function:

  • Call a function with new, which is called "constructor". Any function can be a constructor, just call it with new.
  • As the name suggests, the constructor is used to "construct a new object". Its internal statements will add several properties and methods to the new object to complete the initialization of the object.
  • The constructor must be called with the new keyword, otherwise it cannot work normally. Because of this, the developer agreed that the first letter of the constructor should be capitalized when naming.

Constructor names are capitalized

  • A function name is capitalized. It is not necessarily a constructor
  • Be sure to remember: whether a function is a constructor depends on whether it is called with new. As for the initial capitalization of the name, it is entirely the customary convention of developers
  • If the constructor is called without new, for example
function People(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
//This applies to context rule 1. The function directly calls this to represent window. Therefore, the name, age and sex of the global object change all the time
People('Xiao Ming', 12, 'male');
People('Xiao Hong', 10, 'female');
People('Xiao Gang', 13, 'male');
  • this in the constructor is not the function itself, but an object secretly created by the constructor.
function People(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
var xiaoming = new People('Xiao Ming', 12, 'male'); //{} => xiaoming
var xiaohong = new People('Xiao Hong', 10, 'female');
var xiaogang = new People('Xiao Gang', 13, 'male');
  • Adding methods to objects

function People(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.sayHello = function(){
        console.log("I am"+this.name+", I"+this.age+"Years old, I am a"+this.sex+"Yes.");
    }
    this.sleep = function(){
        console.log(this.name + "Is💤");
    }
}

var tom = new People("tom",12,"male"); 
var jack = new People("jack",13,"male");
var mary  = new People("mary",14,"female");

console.log(tom); //People {name: "tom", age: 12, sex: "male", sayHello: ƒ, sleep: ƒ}
console.log(jack); //People {name: "jack", age: 13, sex: "male", sayHello: ƒ, sleep: ƒ}
console.log(mary); //People {name: "mary", age: 14, sex: "female", sayHello: ƒ, sleep: ƒ}
tom.sayHello();
tom.sleep(); 
jack.sayHello();

Classes and instances

  • Like the blueprint, the class only describes which properties and methods the object will have, but does not specify the value of the property
  • An instance is a concrete object, not a class of objects
  • "Dog" is a class, "Snoopy" is an example, "Xiaobai" is an example

  • Java and C + + are object-oriented languages
  • JavaScript is an object-based language
  • The constructor in JavaScript can be compared with the "class" in OO language. The writing method is indeed similar, but it is essentially different from the real OO language. In subsequent courses, we will also see the unique prototype characteristics completely different from JS and other OO languages.

Prototype and prototype chain

Prototype and prototype chain lookup

What is prototype

  • Any function has a prototype attribute, which means "prototype" in English
  • The value of the prototype attribute is an object, which has the constructor attribute by default and refers back to the function

function sum(a,b){
    return a+b;
}

console.log(sum.prototype); //{constructor: ƒ}
console.log(typeof sum.prototype);  //object
console.log(sum.prototype.constructor === sum); //true

function People(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
var tom = new People("tom",12,'male');
console.log(tom.__proto__ === People.prototype);
  • The prototype attribute of an ordinary function is useless, while the prototype attribute of a constructor is very useful
  • The prototype property of the constructor is the prototype of its instance

Prototype chain lookup

  • JavaScript stipulates that an instance can manage the properties and methods of accessing its prototype, which is called "prototype chain lookup"

  • The hasOwnProperty method can check whether an object really "owns" a property or method
xiaoming.hasOwnProperty('name'); // true
xiaoming.hasOwnProperty('age'); // true
xiaoming.hasOwnProperty('sex'); // true
xiaoming.hasOwnProperty('nationality'); // false
  • The in operator can only check whether a property or method can be accessed by an object, not whether it is its own property or method
function People(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
// Add the nationality attribute to the prototype
People.prototype.nationality = "China";
//Instantiate Tom
var Tom = new People("Tom",12,"male");
console.log(Tom.nationality);
//Instantiate Jack
var Jack = new People("Jack",10,'male');
Jack.nationality = "U.S.A";
console.log(Jack.nationality); //U.S.A,
console.log(Tom.hasOwnProperty("age"));         //true
console.log(Tom.hasOwnProperty("nationality")); //false
console.log(Jack.hasOwnProperty("nationality"));//true
console.log('name' in Tom); 					//true
console.log('nationality' in Tom); 				//true

Add method on prototype

  • In the previous courses, we added the methods directly to the examples:
Solution: write the method to prototype upper function People(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.sayHello = function () {   //Method is added directly to the instance
    	console.log('I am' + this.name);
	};
}
  • The disadvantage of adding methods directly to instances: each instance and the method function of each instance are different functions in memory, resulting in a waste of memory

  • Solution: write the method on the prototype

function People(){
    this.sayHello = function(){
    };
}

var a = new People();
var b = new People();
var c = new People();
console.log(a.sayHello === b.sayHello); //false, the function of each instance is not at one address, which is a bit of a waste of memory

//improvement
function People(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
//Methods should be written on the prototype
People.prototype.sayHello = function(){
    console.log("I am"+this.name+", I this year"+this.age+"Years old!");
}
People.prototype.growUp = function(){
    this.age++;
}
var Jack = new People("Jack",10,'male');
var Tom = new People("Tom",12,"male");

console.log(Jack.sayHello === Tom.sayHello); //true
Jack.sayHello(); //I'm Jack. I'm 10 years old!
Tom.sayHello(); //I'm Tom. I'm 12 years old!
Jack.growUp();
Jack.sayHello(); //I'm Jack. I'm 11 years old

End of prototype chain

function People(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

var xiaoming = new People("xiaoming",12,'male');
console.log(xiaoming.__proto__.__proto__  === Object.prototype);      //true
console.log(Object.prototype.__proto__);                         //null
console.log(Object.prototype.hasOwnProperty("hasOwnProperty"));  //true
console.log(People.prototype.hasOwnProperty("hasOwnProperty"));  //false
console.log(Object.prototype.hasOwnProperty("toString"));       //true

On the prototype chain of arrays

var arr = [1,2,3];
// The following results are true
console.log(arr.__proto__ === Array.prototype);
console.log(arr.__proto__.__proto__ === Object.prototype);
console.log(Array.prototype.hasOwnProperty("push"))
console.log(Array.prototype.hasOwnProperty("splice"))
console.log(Array.prototype.hasOwnProperty("slice"))
console.log(Array.prototype.hasOwnProperty("sort"))

inherit

  • The People class has properties and methods, and the Student class also extends some properties and methods;
  • Student "is a kind of" People ", and the relationship between the two types is" is a kind of "
  • This is the "inheritance" relationship: the Student class inherits from the People class

What is inheritance

  • Inheritance describes the "is a kind of" relationship between two classes. For example, students are a kind of human, so there is an inheritance relationship between human and academic classes
  • People is the parent class (or superclass, base class); Student is the child class (or derived class)
  • Subclasses enrich the parent class and make the class description more specific and detailed

How to implement inheritance in JavaScript

  • The key to inheritance is that the subclass must have all the properties and methods of the parent class, and the subclass should also be able to define its own unique properties and methods
  • It is a common practice to implement inheritance using JavaScript's unique prototype chain feature
  • There will be new inheritance methods in ES6

Inheritance through prototype chain

// Parent, human
function People(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
People.prototype.sayHello = function () {
    console.log('Hello, I'm' + this.name + 'I this year' + this.age + 'Years old');
};
People.prototype.sleep = function () {
    console.log(this.name + 'Start sleeping, zzzzz');
};

// Subclass, student class
function Student(name, age, sex, school, studentNumber) {
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.school = school;
    this.studentNumber = studentNumber;
}
// Key statements to achieve inheritance
Student.prototype = new People();

Student.prototype.study = function () {
    console.log(this.name + 'I am learning');
}
Student.prototype.exam = function () {
    console.log(this.name + 'The exam is in progress. Come on!');
}
// Override and override the sayHello of the parent class
Student.prototype.sayHello = function () {
    console.log('Salute! I am' + this.name + 'I this year' + this.age + 'Years old');
}

// instantiation 
var hanmeimei = new Student('Mei Mei Han', 9, 'female', 'Muke primary school', 100556);

hanmeimei.study();
hanmeimei.sayHello();
hanmeimei.sleep();

var laozhang = new People('Lao Zhang', 66, 'male');
laozhang.sayHello();
laozhang.study(); //Error

Rise to object orientation

Rise to object-oriented small case 1

  • The essence of object-oriented: define different classes and let the instances of classes work
  • Object oriented advantages: clearer programming, tighter code structure, more robust code and more conducive to maintenance
  • Frequently used occasions of object-oriented: occasions requiring encapsulation and reusability (component thinking)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box img{
            width: 80px;
        }
    </style>
</head>
<body>
    <div id="box"></div>

    <script>
        // Define traffic light class
        function TrafficLight() {
            // The color attribute is red at the beginning
            // Red 1, yellow 2, green 3
            this.color = 1;
            // Call your own initialization method
            this.init();
            // Binding listening
            this.bindEvent();
        }
        // Initialization method
        TrafficLight.prototype.init = function() {
            // Create your own DOM
            this.dom = document.createElement('img');
            // Set src properties
            this.dom.src = 'images/' + this.color + '.jpg';
            box.appendChild(this.dom);
        };
        // Binding listening
        TrafficLight.prototype.bindEvent = function() {
            // Backup context. this here refers to the instance of JS
            var self = this;
            // When your dom is clicked
            this.dom.onclick = function () {
                // When clicked, call your own changeColor method
                self.changeColor();
            };
        }
        // Change color
        TrafficLight.prototype.changeColor = function () {
            // Change your color attribute, so as to have a sense of "autonomy". Manage yourself without interfering with other traffic lights
            this.color ++;
            if (this.color == 4) {
                this.color = 1;
            }
            // It's no use changing the color attribute of the light. You have to change the src attribute of your dom
            this.dom.src = 'images/' + this.color + '.jpg';
        };

        // Get the box
        var box = document.getElementById('box');


        // Instantiate 100
        var count = 100;

        while(count--){
            new TrafficLight();
        }
         
    </script>

</body>
</html>
  • Using object-oriented programming, we can solve the problem of a large number of traffic lights conflicting with each other with "component" thinking
  • Object oriented programming, the most important thing is to write classes

Rise to object-oriented small case 2

Rise to object-oriented - colorful ball small case

How to realize multiple ball animation

  • Put each instance of the ball in the same array

{{small ball instance}, {small ball instance}, {small ball instance}, {small ball instance}}

  • Just use a timer to traverse each ball at each frame and call their update method
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: black;
        }

        .ball {
            position: absolute;
            border-radius: 50%;
        }
    </style>
</head>

<body>
    <script>
        // Small ball
        function Ball(x, y) {
            // The attributes x and y represent the coordinates of the center of the circle
            this.x = x;
            this.y = y;
            // Radius attribute
            this.r = 20;
            // transparency
            this.opacity = 1;
            // Small ball background color, select a color randomly from the color array
            this.color = colorArr[parseInt(Math.random() * colorArr.length)];
            // For the x increment and y increment of this small ball, using the do while statement can prevent dX and dY from being zero
            do {
                this.dX = parseInt(Math.random() * 20) - 10;
                this.dY = parseInt(Math.random() * 20) - 10;
            } while (this.dX == 0 && this.dY == 0)

            // initialization
            this.init();
            // Push yourself into the array. Note that this is not the class itself, but the instance
            ballArr.push(this);
        }
        // Initialization method
        Ball.prototype.init = function () {
            // Create your own dom
            this.dom = document.createElement('div');
            this.dom.className = 'ball';
            this.dom.style.width = this.r * 2 + 'px';
            this.dom.style.height = this.r * 2 + 'px';
            this.dom.style.left = this.x - this.r + 'px';
            this.dom.style.top = this.y - this.r + 'px';
            this.dom.style.backgroundColor = this.color;
            // Go up the tree
            document.body.appendChild(this.dom);
        };
        // to update
        Ball.prototype.update = function () {
            // Position change
            this.x += this.dX;
            this.y -= this.dY;
            // Radius change
            this.r += 0.2;
            // Transparency change
            this.opacity -= 0.01;
            this.dom.style.width = this.r * 2 + 'px';
            this.dom.style.height = this.r * 2 + 'px';
            this.dom.style.left = this.x - this.r + 'px';
            this.dom.style.top = this.y - this.r + 'px';
            this.dom.style.opacity = this.opacity;

            // When the transparency is less than 0, you need to delete yourself from the array and DOM elements
            if (this.opacity < 0) {
                // Remove yourself from the array
                for (var i = 0; i < ballArr.length; i++) {
                    if (ballArr[i] == this) {
                        ballArr.splice(i, 1);
                    }
                }
                // Also delete your own dom
                document.body.removeChild(this.dom);
            }
        };


        // Put all the ball instances into an array
        var ballArr = [];

        // Initial color array
        var colorArr = ['#66CCCC', '#CCFF66', '#FF99CC', '#FF6666', 
    '#CC3399', '#FF6600'];

        // Timer, responsible for updating all small ball instances
        setInterval(function () {
            // Traverse the array and call the called update method
            for (var i = 0; i < ballArr.length; i++) {
                ballArr[i].update();
            }
        }, 20);

        // Monitoring of mouse pointer
        document.onmousemove = function (e) {
            // Get the position of the mouse pointer
            var x = e.clientX;
            var y = e.clientY;

            new Ball(x, y);
        };
    </script>
</body>

</html>

Built in object of JS

Packaging

What is packaging

  • Number(), String() and Boolean() are "wrapper classes" for numbers, strings, and Booleans, respectively
  • Many programming languages have the design of "wrapper classes". The purpose of wrapper classes is to enable the basic type values to obtain methods from the prototype of their constructor

give an example

var a = new Number(123);
var b = new String('Muke network');
var c = new Boolean(true);
  • a. Are b and c basic type values? Are they different from ordinary numbers, strings and Boolean values?
var a = new Number(123);
var b = new String('Muke network');
var c = new Boolean(true);

console.log(a);
console.log(typeof a);      // object
console.log(b);
console.log(typeof b);      // object
console.log(c);
console.log(typeof c);      // object

console.log(5 + a);         // 128
console.log(b.slice(0, 2)); // 'muke '
console.log(c && true);     // true

var d = 123;
console.log(d.__proto__ == Number.prototype);       // true

var e = 'Muke network';
console.log(e.__proto__ == String.prototype);       // true
console.log(String.prototype.hasOwnProperty('toLowerCase'));    // true
console.log(String.prototype.hasOwnProperty('slice'));          // true
console.log(String.prototype.hasOwnProperty('substr'));         // true
console.log(String.prototype.hasOwnProperty('substring'));      // true

summary

  • The instances of Number(), String(), and Boolean() are all object types, and their PrimitiveValue property stores their own values
  • The basic type value from new can normally participate in the operation
  • The purpose of wrapper classes is to make basic type values available to methods from the prototype of their constructor

Math object

  • Power sum square: math pow(),Math.sqrt()
  • Rounding up and down: math ceil(),Math.floor()
  • Math.round() can round a number to an integer
console.log(Math.round(3.4)); // 3
console.log(Math.round(3.5)); // 4
console.log(Math.round(3.98)); // 4
console.log(Math.round(3.49)); // 3
  • How can we achieve "rounding to a certain place after the decimal point"?

var a = 12.3567 //Round to the nearest hundredth
console.log(Math.round(a*100)/100); //12.36
  • Math.max() can get the maximum value of the parameter list
  • Math.min() can get the minimum value of the parameter list
console.log(Math.max(6, 2, 9, 4)); // 9
console.log(Math.min(6, 2, 9, 4)); // 2

How to use math Max() find the maximum value of the array?

  • Math.max() requires that the parameter must be "listed", not an array
  • Remember the apply method? It can specify the context of the function and pass in "scattered value" as the parameter of the function in the form of array
var arr = [3, 6, 9, 2];
var max = Math.max.apply(null, arr);
console.log(max); // 9
  • Math.random() can get decimals between 0 and 1
  • In order to obtain the integer in the interval [a, b], this formula can be used:
    • parseInt(Math.random() * (b - a + 1)) + a

Date object

  • Use new Date() to get the date object of the current time, which is an object type value
  • Use new Date(2020, 11, 1) to get the date object of the specified date. Note that the second parameter represents the month, starting from 0, and 11 represents December
  • It can also be written as new Date('2020-12-01 ')

time stamp

  • The time stamp represents the number of milliseconds from a certain time on January 1, 1970
  • Through the getTime() method or date The parse () function can change the date object into a timestamp
  • You can change a timestamp into a date object by writing a new date

Small case: countdown applet

How many days, hours, minutes and seconds are displayed on the page in real time from 9:30 on August 23, 2021

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Only:</h1>
    <h2 id='info'></h2>
    
    <script>
        function countDays(){
            var nowDate = new Date();
            var targetDate = new Date(2021,7,23,9,30);  //2021-8-23-9:30
            var diff = targetDate-nowDate;
            var days = parseInt(diff/(1000*60*60*24));  
            var hours = parseInt(diff%(1000*60*60*24)/(1000*60*60));
            var minutes = parseInt(diff%(1000*60*60)/(1000*60));
            var seconds = parseInt(diff%(1000*60)/1000);
            document.getElementById('info').innerText = days+"day"+hours+"hour"+minutes+'minute'+seconds+'second';
        }
        setInterval(countDays,1000);
    </script>
</body>
</html>

Keywords: Javascript Front-end

Added by diagnostix on Thu, 23 Dec 2021 04:04:39 +0200