javascript object-oriented knowledge points

First, the concept of object-oriented

Object-oriented is a programming idea
Object : attributes (variables) and methods (functions) can be added;
object-oriented writing features:
1. Write the function as a function;
2. The function must be written on the object, and the object is directly taken when calling. Method name ();
3. The functions on the object can be inherited;
4. This points to, the real this cannot be accessed in the event or timer, and needs to be stored outside;

写法示例:
        function 构造函数 (){
            this.属性=??;
        }
        构造函数.prototype.方法=??;

        var 实例=new 构造函数();
        实例.方法();

2. The role of new

The unary operator, which can only be followed by a function, is used to call the function;

The process of calling a function with new:
1. Construct an empty object;
2. Point this inside the function to the created object;
3. Automatically return the object just created after the function is executed, even if there is no return in the function; If there is a return, there will be two situations:
A, if the object is followed by the return, then the object will be returned;
B, if the return is followed by a non-object, then the object created by new at the beginning will be returned;

Note:
1. A function called with new always returns an object, regardless of whether there is a return value;
2. When a function is called with new, this function must be used to create an object, which is called a constructor;

3. Constructor

A function that creates and initializes an object, and must be called with new, otherwise it is no different from an ordinary function;

        functon Person(name,age){
            this.name=name;
            this.age=age;
            this.say=function{
            console.log("my name is"+this.name);
            };
        };

The new ones are all instances of the constructor, and the constructor is the process of instantiation;
the problem of the constructor: performance problems will cause waste of resources;

4. Prototype

Concept: attributes on functions, each function has, its value is an object;

Purpose: Because it is an object, it can put properties and methods on it. If it is combined with the constructor, the object created by the constructor will have the properties and methods on the prototype;

It is recommended to put some common properties and methods on the prototype of the constructor;

Five, proto

Attributes on the object, each object has this attribute; its value is also an object, and its value is the value of the prototype of its corresponding constructor;

Instance.proto === Constructor.prototype; This sentence explains why instances can inherit properties and methods on constructors;

    functon Person(name,age){
        this.name=name;
        this.age=age;
    };
    this.prototype.say=function{
    console.log("my name is"+this.name);
    }; 

    var p1=new Person("peter",18);
  在这个例子中:p1.__proto__=Person.prototype;所以p1才能继承Person构造函数身上的属性和方法;

6. Prototype chain

Relationship between Object and Prototype (link)

Prototype chain search rules:
1. First, it will find it on itself, if there is one, use its own;
2. If not, it will search under the proto of the object, because the proto attribute points to the corresponding constructor The protytpe on the body, when looking for it, is looking for the prototype of the constructor;
3. If there is no prototype on the body, it will continue to look outside until it finds the prototype on the top-level Object;

7. Packaging objects

In js, when we call the properties and methods of strings, booleans, numbers, js will internally convert these basic data types into a corresponding object type (wrapper object), and then call the wrapper object's properties and methods;

The wrapper objects are:
String
Number
Boolear

Note:
1. There is no wrapper object for null and undefined;
2. Only the properties and methods of the corresponding wrapper object can be used for basic data types;

八、hasOwnProperty

hasOwnProperty
function: determine whether a property is on its own object;

Syntax: object.hasOwnProperty(property);

Parameters: property to detect;

Return value:
true own property
false not own property

Note:
1. This method is a method on Object.
2. It will not look for properties outside the prototype chain, but only itself.

Nine, constructor

Constructor
concept: Each object will have this property, which by default points to the constructor corresponding to the object;
this property is not placed on the object, but on the corresponding prototype object;

Role: View the constructor of the object;

Syntax: object.constructor;

Return value: the constructor of the object; it can be used to judge the data type;

 constructor的问题 :constructor的值是可以修改的;

    function Person(name){
        this.name=name;
    }
    var p1=new Person('kaivon');
    console.log(p1);
    console.log(p1.constructor==Person);    //true

    p1.constructor=Array;
    console.log(p1.constructor==Array);     //true

10. toString

Function: Convert the object type to a string;

Note: This method on the system object is on the corresponding prototype; and the method of the constructor written by yourself is on the object prototype of Da

It can be used for type judgment:
Object.prototype.toString.call( );

//用toString做类型判断
        var num=0;                  //[object Number]
        var str='kaivon';           //[object String]
        var b=true;                 //[object Boolean]
        var n=null;                 //[object Null]
        var u=undefined;            //[object Undefined]
        var arr1=[];                //[object Array]
        var obj1={};                //[object Object]
        var fn=function(){};        //[object Function]
        var d=new Date();           //[object Date]
        var re=new RegExp();        //[object RegExp]

        console.log(Object.prototype.toString.call(num));   

11. Shallow copy and deep copy

Basic data type replication:

var num1=123;
var num2=num1;//那么num2和num1就是一样的,**复制了值**

Problems with complex data type replication:

var arr1=[1,2,3];
var arr2=arr1;

arr2.push(4);
//注意这个时候arr1和arr2的值;
console.log(arr2);              //[1,2,3,4]
console.log(arr1);              //[1,2,3,4]

The reason for arr1 and arr2 is the same: when a complex data type is copied, not only the value is copied, but also the reference address, so when arr2 is modified, the address of arr1 and arr2 are actually the same, so the value of arr1 is also changed accordingly ;

Think: So how should we replicate complex data types?

shallow copy ;

var obj1={a:10,b:20};               //如何复制呢?

function copy(obj){
    var newObj={};
    for(var attr in obj){
        newObj[attr]=obj[attr];
    }
    return newObj;
}
var obj2=copy(obj1);
//这时候的obj2和obj1看起来是一样的,但是其实是不同的,有不同的引用地址;

The difference between deep
copy and shallow copy:
1. When all the values ​​in the object to be copied are non-objects, use shallow copy;
2. When there are objects in the object to be copied, use deep copy;

var obj1={
    a:10,
    b:{
        c:20    //这时候对象里面还有对象;这时候怎么办呢?
    }
}

//如果这时候还用上面的浅拷贝的话,那么修改复制后的值,原来对象里面的值也还是会改变,所以要用下面的办法;

function deepCopy(obj){
    if(typeof obj!=="object"){
        return obj;
    }
    //上面的代码是给了一个跳出条件,当传入的条件不是对象的时候就不需要递归了;
    if(obj instanceof Array){
        var newObj=[];
    }else{
        var newObj={};
    }
    for(var attr in obj){
        newObj[attr]=deepCopy(obj[attr]);
        //递归;当对象里面的值还是对象的时候需要用到;
    }
    return newObj;
}

12. Inheritance

concept:

Let one object have the properties and methods of another object, and the properties and methods added by yourself will not affect the original object;

Property inheritance:

Inherit properties by calling the constructor through the call method;

function Person(name,age){
                this.name=name;
                this.age=age;
            }
Person.prototype.say=function(){
                console.log('我叫'+this.name);
            }
//Person相当于一个大类,Coder相当于一个小类,他们是有共同的地方的;
function Coder(name,age,job){
                this.name=name;
                this.age=age;
                this.job=job;
            }
Coder.prototype.say=function(){
                console.log('我叫'+this.name);
            }
//通过属性继承,我们可以将小类和大类共同的部分简化如下:
function Coder(name,age,job){
                Person.call(this,name,age);

    //如果不用call的话,那么this的指向就是window了,所以要用call将指向指到当前的this上面;
                this.job=job;
            }

Method inheritance:

Inheritance through the for in method of the prototype of the constructor you want to inherit;
refer to the code of property inheritance:

for (var attr in Person.prototype){
    if(Person.prototype.hasOwnProperty(attr)){
        Coder.prototype[attr]=Person.prototype[attr];
    }
}

13. Components

concept

Encapsulate an effect or method with an object-oriented method, and only provide users with some related methods and data interfaces; ( modular )

Features

Easy to expand , easy to maintain , and have no impact on each other

The composition of the components:

1. Configuration parameters

Put it in the initialization function;

  • The initialization function is placed on the prototype of the constructor, generally represented by init
  • You need to write a default parameter in the constructor;
function Drag(obj){
    this.disX=0;
    this.disY=0;
    //下面的就是默认参数,下面的函数都要用下面的参数;
    this.settings={
        id:"",          //这是必传的;
        downFn:function{},
        moveFn:function{},
        upFn:function{}
    }
}
//下面这个叫做初始化函数;
Drag.prototype.init=function (opt) {
    //在初始化函数里面,拿用户输入来的参数覆盖默认参数;
    for(var attr in this.settings){
        if(this.settings.hasOwnProperty(attr)){
        //如果默认参数里面有这个属性的话,才会去覆盖;
            this.settings[attr]=opt[attr];
        }
    }
    this.obj=document.getElementById(this.settings.id);
}
//用户传进来的就叫做配置参数;是一个对象;               

2. Methods

functions placed in the prototype;

3. Custom events

  • concept:

    • Events other than those that come with the system are called custom events;
    • It is conducive to multi-person collaborative development and can expand js events;
    • Need to use event binding, event trigger;
    • A custom event is actually a function call that triggers the event in a specified environment;
  • Three elements of custom event:

    • object;
    • event name;
    • event handler;
  • You can use the key-value pair in the object data structure key:valueto associate the event name with the event processing function; put multiple functions into an array, and loop each function in the array;
//定义事件
object.events={
    "事件名1":[fn1,fn2],
    "事件名2":[fn3,fn4,fn5]
}

//调用事件(循环去调用)
  • Code implementation example
//事件绑定器,添加自定义事件;
function customEvent(obj,eventName,fn){
    /*  obj         对象名;
     *  eventName   对象的一个事件名,它的值是一个数组;
     *  fn          事件调用函数,它在数组里面;
     */
    //这里的"||"逻辑符号的意思是左边为真走左边,左边为假走右边;
    obj.events=obj.events||{};
    obj.events[eventName]=obj.events[eventName]||[];
    obj.events[eventName].push(fn);//push方法把函数添加到数组;
}
//事件触发器;
function(obj,eventName){
    //触发的时候要看看对象身上有没有这个事件;
    if(obj.events[eventName]){
        for(var i=0;i<obj.events[eventName].length;i++){
            obj.events[eventName][i].call(obj);
            //注意this的指向,要指向这个obj;
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324770323&siteId=291194637