js Advanced Learning Notes (1)

Object-Oriented, Object Creation, Prototype... .

(Note: Part of the content is from the videos you learned.)

Three Characteristics of Object-Oriented

I. Packaging

A small example is given to illustrate the necessity of packaging.
(1) This is how we write code without object-oriented encapsulation

var divs = document.getElementsByTagName( 'div' );

for(var i = 0; i < divs.length; i++) {

    divs[i].style.border = "1px dotted black";

}

However, when you want to get other tags or traverse the acquired tags, you will repeat the above code, of course, there are several different words, but don't you think you are doing useless work? And make your code look redundant and cumbersome, and your partners are reluctant to work with you. So, with the idea of object-oriented encapsulation is easy to do, please see this code below. .

var itcast = { 
    //Getting Element Module
    getEle: { 
        tag: function (tagName) { 
            return document.getElementsByTagName(tagName); 
        }, 
        id: function (idName) { 
            return document.getElementById(idName); 
        } 
    }, 
    //Setting up css module   
    setCss: { 
        setStyle: function (arr) { 
            for(var i = 0; i < arr.length; i++) { 
                arr[i].style.border = "1px solid #abc"; 
            } 
        }, 
        css: function() {}, 
        addClass: function() {}, 
        removeClass: function() {} 
        // ... 
    } 

};

var divs = itcast.getEle.tag(div);
itcast.setCss.setStyle(divs);

Does this look a lot simpler and less repetitive?

II. Inheritance

Inheritance in JavaScript means that an object does not have some attributes and methods. It takes the attributes and methods of another object for its own use.

(1) Mixed Inheritance for in

var obj = {};
var obj1= {
    name : "inherit",
    sayHello: function() {

        console.log("Hello, I'm the successor.");
    }
}

for(var k in obj1){
    //obj1[k] retrieves every attribute of an object
    //Point grammar is not allowed here when k is used to add new attributes to an object.
    obj[k]=obj1[k];
}
console.log(obj);

(2) prototype inheritance (using sharing)

//(1) Adding new members to prototype objects
function Person(name,age) {
    this.name=name;
    this.age=age;
}
Person.prototype.sayHello=function(){
    alert(this.name+"Hello");
}
var p=new Person("GJ", 18);
p.sayHello();

//(2) Direct replacement of prototype objects
function Person(name,age) {
    this.name=name;
    this.age=age;
}
var sister={
    sayHello : function(){
        alert(this.name+"Hello");
    }
}
Person.prototype=sister;
var p=new Person("GJ", 18);
p.sayHello();

//(3) Adding members to prototype objects by means of blending
function Person(name,age) {
    this.name=name;
    this.age=age;
}
var sister={
    sayHello : function(){
        alert(this.name+"Hello");
    }
}

for(var i in sister){
    Person.prototype[i]=sister[i];
}
var p=new Person("GJ", 18);
p.sayHello();
//Note: This approach is likely to replace the original object in the prototype.

(3) The Role of Prototype Inheritance

———— 1) Extending built-in objects
function MyArray(){
    //You can add the method you want to add here (inheriting all Array attributes and methods below)
}
MyArray.prototype= [];
var NewArray=new MyArray();
NewArray.push(1);
NewArray.push(2,3,4);
alert(NewArray);

3. Polymorphism

js does not correspond to the expression, and is commonly used in strongly typed languages.
In short, it uses variables of the parent class to accept objects of the subclass.

How to create objects

(1) Object literal quantity

Disadvantage: Only one object can be created, and the reusability is poor. If the code of creating multiple objects is too redundant.

var obj = {
    name: "Literal",
    type: "Object",

}

(2) Use constructors

Defect: If you want to create a similar object, you will generate a lot of code

var box=new Object();
box.name='GJ';
box.age='18';
box.run=function() {
 return this.name+this.age+'In operation...'
}

(3) Encapsulating simple factory functions (not recommended)

It solves the problem of repeated instantiation, but there's still a problem of identification, because it's impossible to figure out which object they're actually an instance of.

function createBox(name,age) {
    var obj=new object();
    obj.name= name;
    obj.age=age;
    box.run=function() {
     return this.name+this.age+'In operation...'
    }
    return obj;
}
var obj = createBox('Gj',18);

(4) Custom constructor

It not only solves the problem of repeated instantiation, but also solves the problem of object recognition.
The default return is a newly created object. If we write our own return statement, the return is a null value or a basic data type, and the return is a newly created object; if the return is an object type value, it will be replaced by the return statement.

function Box(name,age) {
    this.name=name;
    this.age=age;
    this.run=function() {
         return this.name+this.age+'In operation...'
    }
}
var box1=new Box('GJ',100);
alert(box1.run());

(5) Prototype

  • What is the prototype?
    ——- When the constructor is created, the system defaults to create and associate a prototype with the constructor.
  • What can prototypes do?
    ——- Attributes and methods in the prototype can be used by objects created using this constructor
  • How to access the prototype of constructor
    ——- Constructor. prototype
  • How to add attributes and methods to prototype objects
    —— Use dynamic properties of objects
    Note: When using an object to access attributes and methods, first look inside the object itself, if found, use it directly, and if not, use the prototype.
function Person(name,status) {
    this.name=name;
    this.status=status;
    this.act=function(){
        console.log("prototype")
    }
}
var p = new Person("xyz","single");

Person.prototype.move = function() {
    console.log("I want to do sports.");
}
p.move();

(6) Notices for using prototype

  • When accessing attributes with objects, if you can't find them in yourself, go to the prototype. However, when using point grammar for attribute duplication, it does not go to the prototype to find the attribute. If the attribute does not exist in the object, it will add the attribute to the object. If the attribute exists in the object, modify the attribute.
  • If an attribute in a prototype is a property of a reference type, then all pairs share that property, and an object modifies the members of that reference type property, all other objects associated with the prototype object will be affected.
  • In general, only methods that need to be shared are placed in the prototype.

(7) Prototype Chain

1. What is the prototype chain?
    Each constructor has a prototype object
    Every object has a constructor
    The prototype of each constructor is an object
    So this prototype object also has constructors
    Then the constructor of the prototype object will have the prototype object as well.
    In this way, a chain structure is formed, which is called prototype chain.
2. Basic Forms of Prototype Chain Structure
function Person(name){
    this.name=name;
}
var w=new Person();

//p ---> Person.prototype --->Object.prototype---->null

Principles of Attribute Search
—— 1. When accessing a member of an object, it will first find out whether it has been used directly by itself.
—— 2. If it is not found, then go to the prototype object of the current object to find, if it finds direct use.
—— 3. If it is not found, continue to find the prototype object of the prototype object. If it is found, use it directly.
—— 4. If not, continue to look up until Object.prototype, and if not, report an error.

(8) Common members of Object.prototype

member describe
Object.prototype.proto Point to the object used as a prototype when the object is instantiated.
Object.prototype.hasOwnProperty() Returns a Boolean value indicating whether an object contains a specified property that is inherited by a non-prototype chain.
Object.prototype.isPrototypeOf() Returns a Boolean value indicating whether the specified object is in the prototype chain of the object.
Object.prototype.toString() Returns the string representation of the object.
Object.prototype.valueOf() Returns the original value of the specified object.

supplement

I. Use of function

(1) Grammar

—— All parameters of the --- Function function are strings
—— The Function is to combine all the parameters into a Function.
—— If only one parameter is passed, then the function must be the body of the function.
—— - 2. If multiple parameters are passed, the last parameter represents the body of the function, and the previous parameter represents the parameters of the function to be created.
—— - 3. If you don't pass parameters, you create an empty function

// Exercise: Use Function to create a function to find the maximum of three numbers.
var max = new Function("a", "b", "c", "return (a > b ? a : b)> c ? (a > b? a : b):c;");

(2) How to solve the problem of too long code in function

1. String splicing can be used to wrap lines of code

 var max = new Function("arr",
         "var maxNum = arr[0];" +
         "for(var i = 1;i<arr.length;i++){" +
         "if(maxNum < arr[i]){" +
         "maxNum = arr[i];" +
         "}" +
         "}" +
         "return maxNum;"
 )

 console.log(max([1, 2, 3, 44, 5, 6]));

2. Write the code in the template tag to get the content of the tag.

 window.onload =function () {
     var script = document.getElementById("funcContent");
     var str = script.innerHTML;
     var max = new Function("arr", str);
     console.log(max([1, 2, 3, 44, 5, 6]));
 }

 <script type="text/template" id="funcContent">
    var maxNum = arr[0];
    for(var i = 1; i<arr.length; i++){
        if(maxNum < arr[i]){
            maxNum = arr[i];
        }
    }
    return maxNum;
</script>

3. Use back quotation marks (`) to quote strings, and you can wrap lines.

ES6 grammar (rarely implemented by browsers) uses the upper left corner of the keyboard to represent the delimiter of a line-changeable string. Previously, we used single or double quotation marks to represent a literal quantity of a string. In ES6, we can use reverse quotation marks to represent the line-changeable string.

//This is the grammar in es6. There is compatibility problem.

 var str = `adfafdsa
            asdfas`;

        console.log(str);

(3) the difference between function and eval

Let's start with eval
The eval function can be used to convert strings into JavaScript code and run
var str = "var a = 10";
eval(str);
console.log(a);
When using eval to parse JSON format strings, it resolves {} into blocks of code instead of literal quantities of objects. The solution is:
1. Stitching "var o =" in front of JSON-formatted strings
2. By enclosing strings in JSON format with (), you don't parse {} into blocks of code, but expressions.

var jsonData = '({"name":"zs", "age":18})';
  var o = JSON.parse(jsonData);
     console.log(o);

eval("var o = "+ jsonData);
var o = eval(jsonData);
console.log(o);

1. Common: Strings can be converted into js code
2. Differences:
1) function creates functions that are not called directly, but can only be executed manually.
2) After eval converts the string into code, it executes directly

(4) arguments

An object within a function that, by default, stores all incoming arguments in turn (a pseudoarray) when the function is called
arguments.length: Can be used to represent the number of arguments passed in

(5) Static and instance members

Static members: the attributes and methods of constructors
Instance Members: The attributes and methods of an instance

function Person(){
    this.name = "zs",
    this.sayHello = function(){
        console.log("Hello World");
    }
}

//The following sayHi method is the constructor's own method, which is the static method.
Person.sayHi = function(){
    console.log("I'm a Person");
}

//Prototype attributes belong to constructors, so prototype attributes are static attributes
Person.prototype = {};
var p = new Person();

//Here the name is the attribute of the instance object created by the constructor, so it is the instance attribute.
p.name = "GJ";


//Here, sayHello is also a method of creating instance objects from constructors, so it is an instance method.
p.sayHello();


//In jQuery, $("#id") is an instance, so they are all instance members.
$("#id").css();
$("#id").text();

//Like this, it's a tool method inside jQuery, and it's a static method.
$.trim();
$.each();
$.extend();

//Use tool methods as static members
//Use object-related methods as instance members

Front-end Xiaobai: What's wrong with what you've written down or what you need to improve? I'd like to point out that I can't thank you enough.
Tip: It will be revised and supplemented later.

Keywords: Attribute JSON Javascript JQuery

Added by lifeless on Tue, 25 Jun 2019 03:57:05 +0300