Object-oriented programming of JavaScript design patterns (object-oriented programming,oop) (i)

Source: Internet
Author: User
When interviewing, you will always be asked, what is your understanding of javascript object-oriented?
Object-oriented programming (OOP) is a programming paradigm. It talks about objects as the basic unit of program design, and encapsulates programs and data to improve program reuse, flexibility and scalability.

1. An example

There is such a requirement: to make a verification form function, only need to verify the user name, email, password, etc.

I feel like I wrote it in the project product development

function checkName () {
    // Verify name
}
function checkEmail () {
    // Verify email
}
function checkPassword () {
    // Verification code password
}
Declared three global variables,

The following is to create 3 functions and save them in variables to achieve your function, and what you write is to put your variable name after the function, which also represents your variables, so declare 3 global variables.

// Create 3 functions and save them in variables
var checkName = function () {
    // Verify name
}
var checkEmail = function () {
    // Verification code mailbox
}
var checkPassword = function () {
    //verify password
}
There is no problem in terms of function, but if someone else defines the same method, it will overwrite the original function, and this mutual coverage problem is not easy to detect.

We can store these inspection functions in a variable, which reduces the risk of overwriting and being overwritten.

(1) Use the object to collect variables

Objects, he has attributes and methods, we access the attributes or methods, can be traversed down through the dot syntax query, we can create a detection object, we put the method inside.

var CheckObject = {
    checkName: function () {
        // Verify name
    },
    checkEmail: function () {
        // Verify email
    },
    checkPassword: function () {
        //verify password
    }
}
At this time, we use all functions as methods of CheckObject object, so that we have only one object, such as check name CheckObject.checkName ().

 

(2) Another form of object

First declare an object, and then add methods to him. In JavaScript, functions are also objects.

var CheckObject = function () {};
CheckObject.checkName = function () {
    // Verify name
}
CheckObject.checkEmail = function () {
    // Verify email
}
CheckObject.checkPassword = function () {
    //verify password
}
But when others want to use the object method you wrote, it is more troublesome, because this object cannot be copied (this object class can not inherit these methods when creating a new object with the new keyword).

 

(3) True and false objects

If you want to simply copy it, you can put these methods in a function object.

var CheckObject = function () {
    return {
        checkName = function () {
            // Check name
        },
        checkEmail = function () {
            // Check mailbox
        }
        checkPassword = function () {
            // Check password
        }
    }
}
Each time we call this function, we return the previous object, and every time someone calls this function, we will return a new object. In this way, each of us will not affect each other when using it, for example, to check the mailbox like this:

var a = CheckObject ();
a.checkEmail ();
 

(4) The class can also

Although the requirement is completed by creating a new object, it is not a real way of creating a class, and the creation of object a has no relationship with the object CheckObject. The returned object has nothing to do with the CheckObject object.

var CheckObject = function () {
    this.checkName = function () {
        // Verify name
    }
    this.checkEmail = function () {
        // Verify email
    }
    this.checkPassword = function () {
        //verify password
    }
}
The above object can be regarded as a class, we can create without using the create object method, since it is a class, use the keyword new to create

var a = new CheckObject ();
a.checkEmail ();
In this way, you can create an object with the CheckObject class, and the rest of us can instantiate the class (create an object with the class), so that everyone has a set of methods.

 

(5) A detection class

Through the definition of this, every time a new object is created through the new keyword, the newly created object will copy the attribute on the this of the class, so the newly created object will have its own set of methods, but sometimes it causes very high consumption Luxury, we need to deal with it.

var CheckObject = function () {};
CheckObject.prototype.checkName = function () {
    // Verify name
}
CheckObject.prototype.checkEmail = function () {
    // Verify email
}
CheckObject.prototype.checkPassword = function () {
    //verify password
}
When creating an object instance in this way, the methods of the created objects are all one, because they need to rely on the prototype prototype to find one by one, and the found method is the same, but the prototype is written many times, you can write

var CheckObject = function () {};
checkObject.prototype = {
    checkName: function () {
        // Verify name
    },
    checkEmail: function () {
        // Verify email
    },
    checkPassword: function () {
    //verify password
    }
}
The above two methods cannot be mixed.

If you assign a new object to the prototype object of the object later, it will override the previous method of assigning the prototype object.

var a = new CheckObject ();
a.checkName ();
a.checkEmail ();
a.checkPassword ();
 

(6) The method can also be used like this

1, this object

var CheckObject = {
    checkName: function () {
    // Verify name
    return this;
    },
    checkEmail: function () {
    // Verify email
    return this;
    },
    checkPassword: function () {
    //verify password
    return this;
    }
}
use:

CheckObject.checkName (). CheckEmail (). CheckPassword ();
 

2. The prototype object of the class

var CheckObject = function () {};
CheckObject.prototype = {
    checkName: function () {
    // Verify name
    return this;
    },
    checkEmail: function () {
    // Verify email
    return this;
    },
    checkPassword: function () {
    //verify password
    return this;
    }
}
But when you use it, you need to create it

var a = new CheckObject ();
a.checkName (). checkEmail (). checkPassword ();
 

(7) Function ancestor

For example, you want to add a method for checking mailboxes to each function.

Function.prototype.checkEmail = function () {
    // Check mailbox

This method is relatively simple to use,

1. Function form

var f = function () {};
f.checkEmail ();
2. The form of the class

var f = new Function ();
f.checkEmail ();
In this way, there is no problem in principle, but it pollutes the global native object Function, so that the functions created by others will also be polluted by the functions you create, causing unnecessary overhead, but you can abstract a functional method that adds methods uniformly . Methods as below:

Function.prototype.addMethod = function (name, fn) {
    this [name] = fn;
}
At this time, if you want to add email verification method and name verification method, you can use

var methods = function () {};
//or
var methods = new Function ();
methods.addMethod (‘checkName’, function () {
// Verify name
})
methods.addMethod (‘checkEmail’, function () {
// Verify email
})
methods.checkName ();
methods.checkEmail ();
 

(8) Chain addition

If you want to add in a chain, return this in addMethods, you can

Function.prototype.addMethod = function (name, fn) {
    this [name] = fn;
    return this;
}
If you want to add methods, you can do this:

var methods = function () {};
methods.addMethod (‘checkName’, function () {
   // Verify name
}). addMethod (‘checkEmail’, function () {
   // Verify email
});
What should I do if I want to use it in a chain?

Since adding methods can return this to implementation, is it true that every method added returns this?

var methods = function () {};
methods.addMethod (‘checkName’, function () {
   // Verify name
   return this;
}). addMethod (‘checkEmail’, function () {
   // Verify email
   return this;
})
have a test:

methods.checkName (). checkEmail ();
 

(9) Change to another way of use

1. Functional call

Function.prototype.addMethod = function (name, fn) {
    this [name] = fn;
    return this;
}
2. Type call

Function.prototype.addMethod = function (name, fn) {
    this.prototype [name] = fn;
    return this;
}
Use the type call, can not be used directly, you need to create a new object through the new keyword

var m = new Methods ();
m.checkEmail ();
 

 

JavaScri
The functions in pt are first-class citizens.

 

1. How to implement chained method invocation?

Just use the this keyword in each method in the class to return a reference to the object instance. Each function call returns a new object, which is a CheckObject object on the surface, but actually a new object returned, so that each call will not affect each other.

2. The addMethod method to add multiple methods to the function?

(1) this object

var CheckObject = {
     checkName: function () {
      // Verify name
      return this;
    },
   checkEmail: function () {
      // Verify email
      return this;
    },
 CheckPassword: function () {
      //verify password
      return this;
    },
}
 

(2) The prototype object of the class

var CheckObject = function () {};
CheckObject.prototype = {
     checkName: function () {
     // Verify name
     return this;
    },
    checkEmail: function () {
     // Verify email
     return this;
     },
     checkPassword: function () {
     //verify password
     return this;
    }
}
 

Object-oriented programming (OOP) of javaScript design pattern (1)
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.